FaustDerLegende commited on
Commit
d8b21f8
·
verified ·
1 Parent(s): 645a7cd

Upload folder using huggingface_hub (part 21)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +8 -0
  2. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py +143 -0
  3. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py +114 -0
  4. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py +298 -0
  5. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template.py +194 -0
  6. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py +27 -0
  7. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py +17 -0
  8. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/segmented_tree.py +242 -0
  9. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd.py +0 -0
  10. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd_kernel_features.py +790 -0
  11. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/subgraph.py +615 -0
  12. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton.py +0 -0
  13. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_combo_kernel.py +2036 -0
  14. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_split_scan.py +228 -0
  15. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_utils.py +387 -0
  16. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper.py +0 -0
  17. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper_fxir.py +1412 -0
  18. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__init__.py +0 -0
  19. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc +0 -0
  20. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc +0 -0
  21. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc +0 -0
  22. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc +0 -0
  23. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc +0 -0
  24. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/compile_utils.py +145 -0
  25. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py +72 -0
  26. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_combined_scheduling.py +139 -0
  27. .venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_env.py +38 -0
  28. .venv/lib/python3.12/site-packages/torch/_inductor/comm_analysis.py +922 -0
  29. .venv/lib/python3.12/site-packages/torch/_inductor/comm_lowering.py +967 -0
  30. .venv/lib/python3.12/site-packages/torch/_inductor/comms.py +2402 -0
  31. .venv/lib/python3.12/site-packages/torch/_inductor/comms_debug.py +112 -0
  32. .venv/lib/python3.12/site-packages/torch/_inductor/compile_fx.py +0 -0
  33. .venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_async.py +415 -0
  34. .venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_ext.py +729 -0
  35. .venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_subproc.py +92 -0
  36. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__init__.py +0 -0
  37. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__main__.py +81 -0
  38. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc +0 -0
  39. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc +0 -0
  40. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc +0 -0
  41. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc +0 -0
  42. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc +0 -0
  43. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc +0 -0
  44. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc +0 -0
  45. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/subproc_pool.py +867 -0
  46. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/timer.py +55 -0
  47. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/tracked_process_pool.py +113 -0
  48. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/utils.py +72 -0
  49. .venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/watchdog.py +149 -0
  50. .venv/lib/python3.12/site-packages/torch/_inductor/compiler_bisector.py +833 -0
.gitattributes CHANGED
@@ -545,3 +545,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
545
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
546
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
547
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
545
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/simd.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
546
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
547
  .venv/lib/python3.12/site-packages/torch/_inductor/codegen/__pycache__/wrapper.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
548
+ .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/post_grad.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
549
+ .venv/lib/python3.12/site-packages/torch/_inductor/fx_passes/__pycache__/split_cat.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
550
+ .venv/lib/python3.12/site-packages/torch/_inductor/heuristics/template/__pycache__/triton.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
551
+ .venv/lib/python3.12/site-packages/torch/_inductor/runtime/__pycache__/triton_heuristics.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
552
+ .venv/lib/python3.12/site-packages/torch/_refs/__pycache__/__init__.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
553
+ .venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_impls.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
554
+ .venv/lib/python3.12/site-packages/torch/_subclasses/__pycache__/fake_tensor.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
555
+ .venv/lib/python3.12/site-packages/torch/_vendor/quack/__pycache__/gemm_sm100.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_benchmark_request.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ import functools
5
+ import logging
6
+ from ctypes import byref, c_int, c_size_t, c_void_p
7
+ from typing import Any, TYPE_CHECKING
8
+
9
+ import torch
10
+ from torch._inductor import config
11
+ from torch._inductor.autotune_process import (
12
+ BenchmarkRequest,
13
+ GPUDeviceBenchmarkMixin,
14
+ TensorMeta,
15
+ )
16
+ from torch._inductor.codecache import DLLWrapper, ROCmCodeCache
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from collections.abc import Callable, Iterable
21
+
22
+
23
+ log = logging.getLogger(__name__)
24
+
25
+
26
+ class ROCmBenchmarkRequest(GPUDeviceBenchmarkMixin, BenchmarkRequest):
27
+ # Important: Instances of this class have to be serializable
28
+ # across process boundaries. Do not put CUDA Tensors in here!
29
+
30
+ def __init__(
31
+ self,
32
+ kernel_name: str,
33
+ input_tensor_meta: TensorMeta | list[TensorMeta],
34
+ output_tensor_meta: TensorMeta | list[TensorMeta],
35
+ extra_args: Iterable[Any],
36
+ source_code: str,
37
+ ) -> None:
38
+ super().__init__(kernel_name, input_tensor_meta, output_tensor_meta, extra_args)
39
+ self.source_code = source_code
40
+ self.workspace_size: int = 0
41
+ self.workspace: torch.Tensor | None = None
42
+ self.DLL: DLLWrapper | None = None
43
+ self._workspace_size_updated = False
44
+ self.hash_key: str = ""
45
+ self.source_file: str = ""
46
+ self.hash_key, self.source_file = ROCmCodeCache.write(self.source_code, "so")
47
+
48
+ def precompile(self):
49
+ # Prepopulate code cache
50
+ # may happen in separate Threadpool
51
+ log.debug("Precompiling %s", self)
52
+ ROCmCodeCache.compile(self.source_code, "so")
53
+ if config.rocm.generate_test_runner:
54
+ ROCmCodeCache.compile(self.source_code, "exe")
55
+ log.debug("Done precompiling %s", self)
56
+
57
+ def make_run_fn(
58
+ self, *input_tensors: torch.Tensor, out: torch.Tensor
59
+ ) -> Callable[[], None]:
60
+ self.ensure_dll_loaded()
61
+ self.update_workspace_size()
62
+ args = [c_void_p(tensor.data_ptr()) for tensor in list(input_tensors) + [out]]
63
+ size_args = [c_int(arg) for arg in self.extra_args]
64
+ log.debug(
65
+ "make_run_fn: self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s",
66
+ self.kernel_name,
67
+ self.source_file,
68
+ self.hash_key,
69
+ self.DLL,
70
+ args,
71
+ self.extra_args,
72
+ )
73
+ stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream)
74
+ run_method = getattr(self.DLL, self.kernel_name)
75
+ workspace_ptr = c_void_p(0)
76
+ if self.workspace_size > 0:
77
+ self.workspace = torch.zeros(
78
+ (self.workspace_size + 7) // 8,
79
+ dtype=torch.float64,
80
+ device=out.device,
81
+ )
82
+ workspace_ptr = c_void_p(self.workspace.data_ptr())
83
+
84
+ # Generate partial function.
85
+ return functools.partial(
86
+ run_method,
87
+ *args,
88
+ *size_args,
89
+ None, # null workspace size ptr
90
+ workspace_ptr, # set workspace ptr,
91
+ stream_ptr,
92
+ )
93
+
94
+ def update_workspace_size(self) -> None:
95
+ if self._workspace_size_updated:
96
+ return
97
+ self.ensure_dll_loaded()
98
+ unique_input_count = len(
99
+ dict.fromkeys(meta.name for meta in self.input_tensor_meta)
100
+ )
101
+ args = [c_void_p(None) for _ in range(unique_input_count + 1)]
102
+ stream_ptr = c_void_p(torch.cuda.current_stream().cuda_stream)
103
+
104
+ run_method = getattr(self.DLL, self.kernel_name)
105
+ # Retrieve workspace_size and initialize workspace.
106
+ c_workspace_size = c_size_t()
107
+ size_args = [c_int(arg) for arg in self.extra_args]
108
+ run_method(
109
+ *args, # input ptrs and output ptrs
110
+ *size_args,
111
+ byref(
112
+ c_workspace_size
113
+ ), # set workspace size ptr to retrieve workspace size
114
+ None, # null workspace ptr
115
+ stream_ptr,
116
+ )
117
+ torch.cuda.synchronize() # shake out any CUDA errors
118
+ self.workspace_size = c_workspace_size.value
119
+ log.debug(
120
+ "update_workspace_size called: new workspace size=%d, self.kernel_name=%s, self.source_file=%s, self.hash_key=%s, self.DLL=%s, args=%s, self.extra_args=%s",
121
+ self.workspace_size,
122
+ self.kernel_name,
123
+ self.source_file,
124
+ self.hash_key,
125
+ self.DLL,
126
+ args,
127
+ self.extra_args,
128
+ )
129
+ self._workspace_size_updated = True
130
+
131
+ def ensure_dll_loaded(self):
132
+ if self.DLL is None:
133
+ self.DLL, self.hash_key, self.source_file = ROCmCodeCache.load(
134
+ self.source_code, "so"
135
+ )
136
+
137
+ def cleanup_run_fn(self) -> None:
138
+ if self.DLL is not None:
139
+ self.DLL.close()
140
+ self.workspace = None
141
+
142
+ def __str__(self) -> str:
143
+ return f"{self.kernel_name=}, {self.source_file=}, {self.hash_key=}"
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_cpp_scheduling.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections.abc import Sequence
4
+ from typing import cast, TypeGuard
5
+
6
+ from ... import config
7
+ from ...codecache import code_hash, get_path
8
+ from ...scheduler import BaseSchedulerNode, BaseScheduling, SchedulerNode
9
+ from ...utils import get_fused_kernel_name, get_kernel_metadata, sympy_product
10
+ from ...virtualized import V
11
+ from ..common import IndentedBuffer
12
+ from .rocm_template_buffer import ROCmTemplateBuffer
13
+
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ class ROCmCPPScheduling(BaseScheduling):
19
+ """
20
+ Partial Scheduling implementation for ROCm C++ Kernels.
21
+ This class is intended to be used in combination with TritonScheduling,
22
+ and delegated to by CUDACombinedScheduling.
23
+
24
+ It handles fusion decisions and ROCm C++ specific template code generation.
25
+ """
26
+
27
+ def group_fn(self, sizes):
28
+ return tuple(V.graph.sizevars.simplify(sympy_product(s)) for s in sizes)
29
+
30
+ @staticmethod
31
+ def is_rocm_cpp_template(node: BaseSchedulerNode) -> TypeGuard[SchedulerNode]:
32
+ return isinstance(node, SchedulerNode) and isinstance(
33
+ node.node, ROCmTemplateBuffer
34
+ )
35
+
36
+ def can_fuse_vertical(
37
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
38
+ ) -> bool:
39
+ return False
40
+
41
+ def define_kernel(self, src_code: str, node_schedule) -> str:
42
+ wrapper = V.graph.wrapper_code
43
+ if src_code in wrapper.src_to_kernel:
44
+ kernel_name = wrapper.src_to_kernel[src_code]
45
+ else:
46
+ fused_name = (
47
+ get_fused_kernel_name(node_schedule, config.triton.descriptive_names)
48
+ if config.triton.descriptive_names
49
+ else ""
50
+ )
51
+ kernel_name = "_".join(["rocm", fused_name, wrapper.next_kernel_suffix()])
52
+ # use the original src_code as the key
53
+ wrapper.src_to_kernel[src_code] = kernel_name
54
+ src_code = src_code.replace("KERNEL_NAME", kernel_name)
55
+
56
+ _, _, kernel_path = get_path(code_hash(src_code), "py")
57
+
58
+ compile_wrapper = IndentedBuffer()
59
+ compile_wrapper.writeline("async_compile.rocm(r'''")
60
+ compile_wrapper.splice(src_code, strip=True)
61
+ compile_wrapper.writeline(
62
+ f"''', 'so', aot_compile={str(V.graph.aot_mode)})"
63
+ )
64
+
65
+ metadata_comment = f"# kernel path: {kernel_path}"
66
+ origins, detailed_origins = get_kernel_metadata(node_schedule, wrapper)
67
+ metadata_comment += "\n" + origins + "\n" + detailed_origins
68
+ wrapper.define_kernel(
69
+ kernel_name, compile_wrapper.getvalue(), metadata_comment
70
+ )
71
+
72
+ # For JIT cpp_wrapper, the kernel call site emits a bare
73
+ # `extern "C"` symbol reference; compile the .so now so the
74
+ # wrapper compile can link against it via extra_flags.
75
+ # Autotune compiled a .so for the unfused kernel name
76
+ # (e.g. rocm_<hash>), but at codegen time the kernel name
77
+ # gains a descriptive prefix (rocm_fused_mm_<hash>), so the
78
+ # exported symbol differs and we need a fresh compile.
79
+ if V.graph.cpp_wrapper and not V.graph.aot_mode:
80
+ from ...codecache import ROCmCodeCache
81
+
82
+ so_path, _, _ = ROCmCodeCache.compile(src_code, "so")
83
+ wrapper.external_kernel_libs.add(so_path)
84
+ return kernel_name
85
+
86
+ def codegen_template(
87
+ self,
88
+ template_node: BaseSchedulerNode,
89
+ epilogue_nodes: Sequence[BaseSchedulerNode],
90
+ prologue_nodes: Sequence[BaseSchedulerNode],
91
+ ):
92
+ """
93
+ Codegen a ROCm template, possibly with fused epilogues
94
+ """
95
+ if not self.is_rocm_cpp_template(template_node):
96
+ raise AssertionError(
97
+ "Template node passed to ROCmScheduler.codegen_template must be a SchedulerNode that wraps a ROCmTemplateBuffer"
98
+ )
99
+ _, (_numel, rnumel) = template_node.group
100
+ if rnumel != 1:
101
+ raise AssertionError(f"expected rnumel == 1, got {rnumel}")
102
+ ctb: ROCmTemplateBuffer = cast(ROCmTemplateBuffer, template_node.node)
103
+ kernel, render = ctb.make_kernel_render(ctb) # type: ignore[misc]
104
+ with kernel:
105
+ template_node.mark_run()
106
+ src_code = render()
107
+
108
+ with V.set_kernel_handler(kernel):
109
+ node_schedule = [template_node]
110
+ kernel_name = self.define_kernel(src_code, node_schedule)
111
+ self.codegen_comment(node_schedule, kernel_name)
112
+ kernel.call_kernel(kernel_name, ctb)
113
+ V.graph.removed_buffers |= kernel.removed_buffers
114
+ self.free_buffers_in_scheduler()
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_kernel.py ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+ from collections.abc import Callable, Sequence
4
+ from typing import Any, TYPE_CHECKING
5
+
6
+ import torch._inductor.config as config
7
+ from torch._inductor.codegen.cpp_wrapper_cpu import CppWrapperCpu
8
+ from torch._inductor.utils import do_bench_using_profiling
9
+
10
+ from ...ir import Buffer, ChoiceCaller, IRNode, Layout, PrimitiveInfoType, TensorBox
11
+ from ...virtualized import V
12
+ from ..common import Kernel, OpOverrides, WorkspaceArg, WorkspaceZeroMode
13
+ from ..cpp_utils import CppPrinter
14
+ from .rocm_benchmark_request import ROCmBenchmarkRequest
15
+ from .rocm_template_buffer import ROCmTemplateBuffer
16
+ from .rocm_utils import DTYPE_TO_ROCM_TYPE
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ from torch._inductor.codegen.rocm.rocm_template import ArgInfo, ROCmTemplate
21
+
22
+ log = logging.getLogger(__name__)
23
+
24
+ cexpr = CppPrinter().doprint
25
+
26
+
27
+ def _normalize_idx(index: int, total_length: int) -> int:
28
+ return index if index >= 0 else index + total_length
29
+
30
+
31
+ class ROCmKernel(Kernel):
32
+ """
33
+ Baseclass for ROCm based Kernels
34
+ """
35
+
36
+ overrides = OpOverrides # type: ignore[assignment]
37
+
38
+
39
+ class ROCmTemplateKernel(ROCmKernel):
40
+ """
41
+ Template kernels defined by ROCm in C++.
42
+ """
43
+
44
+ _EXTRA_CPP_ARGS = "size_t* workspace_size, uint8_t* workspace, hipStream_t stream"
45
+
46
+ def __init__(
47
+ self,
48
+ kernel_name: str,
49
+ runtime_arg_info: list["ArgInfo"],
50
+ runtime_arg_values: list[Any],
51
+ ) -> None:
52
+ """
53
+ Initializes a new instance of the ROCmTemplateKernel class.
54
+
55
+ Args:
56
+ kernel_name (str): The name of the kernel.
57
+ """
58
+ super().__init__()
59
+ self.kernel_name = kernel_name
60
+ # Mapping from arg name to IRNode.
61
+ self.named_nodes: dict[str, IRNode] = {}
62
+ self.runtime_arg_info = runtime_arg_info
63
+ self.runtime_arg_values = runtime_arg_values
64
+
65
+ def get_signature(self):
66
+ return self.signature
67
+
68
+ def def_kernel(
69
+ self,
70
+ inputs: list[IRNode],
71
+ outputs: list[IRNode],
72
+ size_args: list[str],
73
+ names_str: str = "",
74
+ input_reorder: list[int] | None = None,
75
+ ) -> str:
76
+ """
77
+ Hook called from template code to generate function definition and
78
+ needed args.
79
+
80
+ Args:
81
+ inputs: List of input IRNodes
82
+ outputs: List of output IRNodes
83
+ names_str: Comma separated list of input + output argument names.
84
+ input_reorder: The actual order of input nodes.
85
+ e.g. The template might have input argument defined as [X, W, Bias],
86
+ and the actual input passed into this template could be [Bias, X, W].
87
+ In this case, the `input_reorder` would be [2, 0, 1].
88
+ """
89
+ names = [x.strip() for x in names_str.strip().split(",")]
90
+ if len(inputs) + len(outputs) != len(names):
91
+ raise RuntimeError(
92
+ f"{len(inputs) + len(outputs)=} != {len(names)=}, {inputs=}, {outputs=}, {names=}"
93
+ )
94
+
95
+ if input_reorder == [2, 0, 1]:
96
+ input_reorder = [4, 0, 1, 2, 3]
97
+
98
+ if input_reorder is not None:
99
+ if len(inputs) != len(input_reorder):
100
+ raise AssertionError(
101
+ f"expected len(inputs) == len(input_reorder), "
102
+ f"got {len(inputs)} and {len(input_reorder)}"
103
+ )
104
+ else:
105
+ input_reorder = list(range(len(inputs)))
106
+
107
+ for idx in input_reorder:
108
+ name = names[idx]
109
+ node = inputs[idx]
110
+ if node is not None:
111
+ self.named_nodes[name] = node
112
+ self.args.input_buffers[node.get_name()] = name
113
+
114
+ for name, node in zip(names[len(inputs) : len(inputs) + len(outputs)], outputs):
115
+ if node is not None:
116
+ self.named_nodes[name] = node
117
+ self.args.output_buffers[node.get_name()] = name
118
+
119
+ arg_defs, *_ = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE)
120
+
121
+ runtime_arg_defs = [f"{arg.ty} {arg.name}" for arg in self.runtime_arg_info]
122
+
123
+ signature = f"int {self.kernel_name}({', '.join(arg_defs + size_args + runtime_arg_defs)},{self._EXTRA_CPP_ARGS})"
124
+ self.signature = signature
125
+ return signature
126
+
127
+ def call_kernel(
128
+ self,
129
+ name: str,
130
+ node: "ROCmTemplateBuffer", # type: ignore[name-defined]
131
+ ) -> None:
132
+ """
133
+ Generates code to call the kernel through V.graph.wrapper_code.
134
+ used from within torch._inductor.wrapper.PythonWrapperCodegen
135
+
136
+ name: Name of kernel function.
137
+ node: The ROCmTemplateBuffer node which contains information about the kernel, it's fused epilogue nodes
138
+ as well as all required inputs and outputs.
139
+ """
140
+ wrapper = V.graph.wrapper_code
141
+
142
+ arg_types: list[Any]
143
+ if V.graph.cpp_wrapper:
144
+ # Make sure we initialize these kernels since they're exported as
145
+ # C-style symbol names.
146
+ if not isinstance(wrapper, CppWrapperCpu):
147
+ raise AssertionError(
148
+ f"expected wrapper to be CppWrapperCpu, got {type(wrapper)}"
149
+ )
150
+ wrapper.initialized_kernels[name] = self
151
+ # Kinda hacky because we always originally initialize name with "KERNEL_NAME"
152
+ # So, we replace with the real kernel name passed as an arg to this function.
153
+ self.signature = self.signature.replace("KERNEL_NAME", name)
154
+ _, call_args, arg_types = self.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE)
155
+ else:
156
+ _, call_args, _, arg_types = self.args.python_argdefs()
157
+
158
+ kernel_args = []
159
+ for arg in call_args:
160
+ # dynamo wraps unspec variable as 0d CPU tensor, need convert to scalar
161
+ if V.graph.is_unspec_arg(arg):
162
+ arg = arg + ".item()"
163
+ else:
164
+ if not V.graph.cpp_wrapper:
165
+ arg = f"c_void_p({arg}.data_ptr())"
166
+ kernel_args.append(arg)
167
+
168
+ # add size args
169
+ size_args = [
170
+ f"{V.graph.sizevars.simplify(sarg)}" for sarg in node.template.size_args()
171
+ ]
172
+
173
+ if V.graph.cpp_wrapper:
174
+ kernel_args.extend(size_args)
175
+ else:
176
+ kernel_args.extend(f"c_int({sarg})" for sarg in size_args)
177
+
178
+ if V.graph.cpp_wrapper:
179
+ arg_types.extend(["int"] * len(node.template.size_args()))
180
+
181
+ # the runtime args come right after the size args
182
+ kernel_args.extend(self.runtime_arg_values)
183
+ for arg in self.runtime_arg_info:
184
+ arg_types.append(arg.ty)
185
+
186
+ # workspace_size ptr is NULL to mark this call is not intended for retrieving workspace_size.
187
+ # workspace_size should have already been retrieved prior to this call.
188
+ kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None")
189
+ if V.graph.cpp_wrapper:
190
+ arg_types.append("size_t*")
191
+
192
+ if node.get_workspace_size() > 0:
193
+ ws = WorkspaceArg(
194
+ count=node.get_workspace_size(),
195
+ device=V.graph.get_current_device_or_throw(),
196
+ zero_mode=WorkspaceZeroMode.UNINITIALIZED,
197
+ outer_name=WorkspaceArg.unique_name(),
198
+ )
199
+ wrapper.generate_workspace_allocation(ws)
200
+ data_ptr = f"{ws.outer_name}.data_ptr()"
201
+ kernel_args.append(
202
+ data_ptr if V.graph.cpp_wrapper else f"c_void_p({data_ptr})"
203
+ )
204
+ else:
205
+ ws = None
206
+ kernel_args.append("nullptr" if V.graph.cpp_wrapper else "None")
207
+ if V.graph.cpp_wrapper:
208
+ arg_types.append("uint8_t*")
209
+ wrapper.generate_kernel_call(
210
+ name,
211
+ kernel_args,
212
+ triton=False,
213
+ arg_types=arg_types,
214
+ )
215
+ if ws:
216
+ wrapper.generate_workspace_deallocation(ws)
217
+
218
+
219
+ class ROCmTemplateCaller(ChoiceCaller):
220
+ """
221
+ ROCmTemplateCaller
222
+
223
+ This class represents a caller for ROCm template kernels. It is a subclass of ChoiceCaller.
224
+ Attributes:
225
+ name (str): The name of the caller.
226
+ category (str): The category of the caller.
227
+ bmreq (ROCmBenchmarkRequest): The benchmark request for the caller.
228
+ template_buffer (ROCmTemplateBuffer): The template buffer for the caller.
229
+ """
230
+
231
+ def __init__(
232
+ self,
233
+ name: str,
234
+ category: str,
235
+ input_nodes: list[Buffer],
236
+ layout: Layout,
237
+ make_kernel_render: Callable[
238
+ [ROCmTemplateBuffer, Sequence[IRNode] | None], str
239
+ ],
240
+ bmreq: ROCmBenchmarkRequest,
241
+ template: "ROCmTemplate", # type: ignore[name-defined]
242
+ info_kwargs: dict[str, PrimitiveInfoType | list[PrimitiveInfoType]] | None, # type: ignore[type-arg]
243
+ ) -> None:
244
+ super().__init__(name, input_nodes, layout, description="")
245
+ self.category = category
246
+ self.make_kernel_render = make_kernel_render
247
+ self.bmreq = bmreq
248
+ self.template = template
249
+ self.info_kwargs = info_kwargs
250
+
251
+ def precompile(self) -> None:
252
+ if self.bmreq is None:
253
+ raise AssertionError("expected self.bmreq to be set")
254
+ self.bmreq.precompile()
255
+
256
+ def benchmark(self, *args, out) -> float:
257
+ if self.bmreq is None:
258
+ raise AssertionError("expected self.bmreq to be set")
259
+ if config.profile_bandwidth_with_do_bench_using_profiling:
260
+ algo = self.bmreq.make_run_fn(*args, out=out)
261
+ return do_bench_using_profiling(algo)
262
+ return self.bmreq.benchmark(*args, out=out)
263
+
264
+ def __str__(self) -> str:
265
+ return f"ROCmTemplateCaller(source_file={self.bmreq.source_file}, {self.info_dict()})"
266
+
267
+ def call_name(self) -> str:
268
+ return f"rocm_template_kernels.{self.name}"
269
+
270
+ def hash_key(self) -> str:
271
+ return "-".join(
272
+ [
273
+ self.category,
274
+ self.bmreq.hash_key,
275
+ ]
276
+ )
277
+
278
+ def info_dict(self) -> dict[str, PrimitiveInfoType | list[PrimitiveInfoType]]:
279
+ """Information returned here is logged to the autotune log file when that is enabled."""
280
+ return {
281
+ "backend": "ROCm",
282
+ "name": self.name,
283
+ **dict(self.info_kwargs["op"].dict_items()), # type: ignore[union-attr, index]
284
+ }
285
+
286
+ def output_node(self) -> TensorBox:
287
+ self.bmreq.update_workspace_size()
288
+ buffer = ROCmTemplateBuffer(
289
+ layout=self.layout,
290
+ inputs=self.input_nodes,
291
+ make_kernel_render=self.make_kernel_render,
292
+ workspace_size=self.bmreq.workspace_size,
293
+ template=self.template,
294
+ )
295
+ # Pass KTC annotation to the buffer for encoding
296
+ if "ktc" in self.annotations:
297
+ buffer.annotations["ktc"] = self.annotations["ktc"]
298
+ return TensorBox.create(buffer)
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import itertools
4
+ import logging
5
+ from collections.abc import Sequence
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+ from unittest.mock import patch
9
+
10
+ from ...autotune_process import TensorMeta
11
+ from ...ir import Buffer, IRNode, Layout
12
+ from ...utils import IndentedBuffer, unique
13
+ from ...virtualized import V
14
+ from ..common import KernelTemplate
15
+ from .rocm_benchmark_request import ROCmBenchmarkRequest
16
+ from .rocm_kernel import ROCmTemplateCaller, ROCmTemplateKernel
17
+ from .rocm_template_buffer import ROCmTemplateBuffer
18
+ from .rocm_utils import DTYPE_TO_ROCM_TYPE
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ # FIXME: unify with the CUDA version
25
+ @dataclass(frozen=True)
26
+ class ArgInfo:
27
+ name: str
28
+ ty: str
29
+
30
+
31
+ class ROCmTemplate(KernelTemplate):
32
+ index_counter = itertools.count()
33
+ gfx9_threads_per_warp = 64
34
+
35
+ def __init__(
36
+ self,
37
+ name: str,
38
+ input_nodes: list[Buffer],
39
+ layout: Layout,
40
+ input_reorder: list[int] | None = None,
41
+ ) -> None:
42
+ """
43
+
44
+ Baseclass for ROCm C++ Templates, derived from KernelTemplate. Not to be instantiated directly.
45
+
46
+ Args:
47
+ name (str): The name of the ROCmTemplate object.
48
+ input_nodes (List[IRNode]): A list of input IRNodes.
49
+ layout (Layout): The layout of the output buffer / tensor.
50
+ input_reorder (Optional[List[int]]): An optional list that specifies the order of the input nodes.
51
+
52
+ """
53
+ super().__init__(name)
54
+ self.input_nodes = input_nodes
55
+ self.output_node: Buffer = Buffer(name="buf_out", layout=layout)
56
+ self.input_reorder = input_reorder
57
+ self.layout = layout
58
+
59
+ def generate( # type: ignore[override]
60
+ self,
61
+ **kwargs,
62
+ ) -> ROCmTemplateCaller:
63
+ """
64
+ Generates the ROCm template caller object for the given GEMM template and operation. This ROCmTemplateCaller
65
+ may be used to call and benchmark the generated ROCm kernel in a standalone manner to enable Autotuning.
66
+
67
+ Args:
68
+ kwargs: Additional keyword arguments.
69
+
70
+ Returns:
71
+ A ROCmTemplateCaller object representing the generated ROCm template caller.
72
+ """
73
+ kernel_name = f"rocm_{self.name}"
74
+ kernel_hash_name = f"rocm_{self.name}_{next(self.index_counter)}"
75
+ with (
76
+ patch.object(V.graph, "get_dtype", self._fake_get_dtype(self.output_node)),
77
+ ROCmTemplateKernel(
78
+ kernel_name=kernel_name,
79
+ runtime_arg_info=self.get_runtime_arg_info(),
80
+ runtime_arg_values=self.get_runtime_arg_values(**kwargs),
81
+ ) as kernel,
82
+ ):
83
+ code = self.render(kernel=kernel, **kwargs)
84
+ _, call_args, _, _ = kernel.args.python_argdefs()
85
+ log.debug("Autotune key: %s, Generated Code:\n%s", kernel_hash_name, code)
86
+ log.debug(
87
+ "Args: cpp_argdefs: %s, python_argdefs: %s",
88
+ kernel.args.cpp_argdefs(DTYPE_TO_ROCM_TYPE),
89
+ kernel.args.python_argdefs(),
90
+ )
91
+
92
+ input_reorder = (
93
+ self.input_reorder
94
+ if self.input_reorder is not None
95
+ else list(range(len(self.input_nodes)))
96
+ )
97
+ expected_args = list(
98
+ unique(self.input_nodes[idx].get_name() for idx in input_reorder)
99
+ )
100
+ expected_args.extend([self.output_node.get_name()])
101
+ if list(call_args)[: len(expected_args)] != expected_args:
102
+ raise AssertionError(
103
+ (
104
+ call_args,
105
+ expected_args,
106
+ )
107
+ )
108
+
109
+ size_args = (
110
+ self.size_args() if hasattr(self, "size_args") else ()
111
+ ) # subclass should define def size_args()
112
+ # Resolve symbolic sizes to concrete ints for benchmarking only.
113
+ size_args_ints = list(V.graph.sizevars.optimization_hints(size_args))
114
+ # The runtime args come right after the size args
115
+ runtime_args = self.get_runtime_arg_values(**kwargs)
116
+ extra_args = size_args_ints + runtime_args
117
+ bmreq = ROCmBenchmarkRequest(
118
+ kernel_name=kernel_name,
119
+ input_tensor_meta=TensorMeta.from_irnodes(self.input_nodes),
120
+ output_tensor_meta=TensorMeta.from_irnodes(self.output_node),
121
+ extra_args=extra_args,
122
+ source_code=code,
123
+ )
124
+
125
+ def make_kernel_render(
126
+ template_node: ROCmTemplateBuffer,
127
+ epilogue_nodes: Sequence[IRNode] | None = None,
128
+ ):
129
+ kernel = ROCmTemplateKernel(
130
+ kernel_name="KERNEL_NAME",
131
+ runtime_arg_info=self.get_runtime_arg_info(),
132
+ runtime_arg_values=self.get_runtime_arg_values(**kwargs),
133
+ )
134
+ render = functools.partial(
135
+ self.render,
136
+ kernel=kernel,
137
+ template_buffer_node=template_node,
138
+ epilogue_nodes=epilogue_nodes,
139
+ **kwargs, # includes "op" argument in case of CUTLASSGemmTemplate
140
+ )
141
+ return kernel, render
142
+
143
+ return ROCmTemplateCaller(
144
+ kernel_hash_name,
145
+ self.name,
146
+ self.input_nodes,
147
+ self.output_node.get_layout(),
148
+ make_kernel_render,
149
+ bmreq,
150
+ self,
151
+ kwargs,
152
+ )
153
+
154
+ def header(self) -> IndentedBuffer:
155
+ res = IndentedBuffer()
156
+ res.splice(
157
+ """
158
+ #include <exception>
159
+ #include <iostream>
160
+ #include <memory>
161
+ #include <random>
162
+ #include <vector>
163
+ """
164
+ )
165
+ return res
166
+
167
+ def globals(self) -> IndentedBuffer:
168
+ res = IndentedBuffer()
169
+ res.splice(
170
+ """
171
+ // We compile all models with -fvisibility=hidden. Any symbols that need to be
172
+ // exposed in the final shared library must be declared with PT_EXPORT to make
173
+ // them visible.
174
+ #ifdef __GNUC__ // Applies to any compiler with GNU extensions (clang and g++)
175
+ #define PT_EXPORT __attribute__((__visibility__("default")))
176
+ #else
177
+ #ifdef _WIN32
178
+ #define PT_EXPORT __declspec(dllexport)
179
+ #else
180
+ #define PT_EXPORT
181
+ #endif
182
+ #endif
183
+ """
184
+ )
185
+ return res
186
+
187
+ def render(self, **kwargs) -> str:
188
+ raise NotImplementedError
189
+
190
+ def get_runtime_arg_info(self) -> list[ArgInfo]:
191
+ return []
192
+
193
+ def get_runtime_arg_values(self, **kwargs) -> list[Any]:
194
+ return []
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_template_buffer.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Sequence
2
+ from typing import TypeVar
3
+ from typing_extensions import ParamSpec
4
+
5
+ from ...ir import Buffer, Layout, TemplateBuffer
6
+
7
+
8
+ _P = ParamSpec("_P")
9
+ _T = TypeVar("_T")
10
+
11
+
12
+ class ROCmTemplateBuffer(TemplateBuffer):
13
+ def __init__(
14
+ self,
15
+ layout: Layout,
16
+ inputs: Sequence[Buffer],
17
+ make_kernel_render: Callable[_P, _T],
18
+ workspace_size: int,
19
+ template: "ROCmTemplate", # type: ignore[name-defined] # noqa: F821
20
+ ) -> None:
21
+ super().__init__(layout, inputs, make_kernel_render)
22
+ # Global memory (in bytes) needed for this template.
23
+ self.workspace_size = workspace_size
24
+ self.template = template
25
+
26
+ def get_workspace_size(self) -> int:
27
+ return self.workspace_size if self.workspace_size is not None else 0
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/rocm/rocm_utils.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+
3
+
4
+ import torch
5
+
6
+ from ..cpp_utils import DTYPE_TO_CPP
7
+
8
+
9
+ DTYPE_TO_ROCM_TYPE = {
10
+ **DTYPE_TO_CPP,
11
+ torch.float16: "uint16_t",
12
+ torch.float8_e4m3fnuz: "uint8_t",
13
+ torch.float8_e5m2fnuz: "uint8_t",
14
+ torch.float8_e4m3fn: "uint8_t",
15
+ torch.float8_e5m2: "uint8_t",
16
+ torch.bfloat16: "uint16_t",
17
+ }
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/segmented_tree.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ from typing import Generic, TypeVar
3
+
4
+
5
+ T = TypeVar("T")
6
+
7
+
8
+ def _value_or(opt: T | None, default: T) -> T:
9
+ return opt if opt is not None else default
10
+
11
+
12
+ class SegmentedTree(Generic[T]):
13
+ def __init__(
14
+ self,
15
+ values: list[T],
16
+ update_op: Callable[[T, T], T],
17
+ summary_op: Callable[[T, T], T],
18
+ identity_element: T,
19
+ ):
20
+ """
21
+ Initialize a segment tree with the given values and operations.
22
+
23
+ Args:
24
+ values: list of initial values
25
+ update_op: Function to apply when updating a value (e.g., addition)
26
+ summary_op: Function to summarize two values (e.g., min, max, sum)
27
+ identity_element: Identity element for the summary_op (e.g., 0 for sum, float('inf') for min)
28
+
29
+ Raises:
30
+ ValueError: If the input values list is empty
31
+ """
32
+ if not values:
33
+ raise ValueError("Cannot create a segment tree with empty values list")
34
+
35
+ self.n = len(values)
36
+ self.update_op = update_op
37
+ self.summary_op = summary_op
38
+ self.identity = identity_element
39
+
40
+ # Size of segment tree array (next power of 2 * 2)
41
+ # The tree follows a standard heap layout where
42
+ # node `n`'s children are at `2*n` and `2*n+1`.
43
+ # Index 0 is unused.
44
+ self.size = 1
45
+ while self.size < self.n:
46
+ self.size *= 2
47
+ self.size *= 2
48
+
49
+ # Initialize tree and lazy arrays
50
+ self.tree = [identity_element] * self.size
51
+ # The lazy array contains updates to the given node
52
+ # Upon update, we only push updates to the top-most
53
+ # nodes that fully receive the update. We then
54
+ # propagate the update down as required (i.e., when
55
+ # we receive an interval query that neither fully
56
+ # contains the node nor fully doesn't contain the
57
+ # node
58
+ self.lazy: list[T | None] = [None] * self.size
59
+
60
+ # Build the tree
61
+ self._build(values, 1, 0, self.n - 1)
62
+
63
+ def _build(self, values: list[T], node: int, start: int, end: int) -> None:
64
+ """
65
+ Build the segment tree recursively.
66
+
67
+ Args:
68
+ values: Original array of values
69
+ node: Current node index in the segment tree
70
+ start: Start index of the segment
71
+ end: End index of the segment
72
+ """
73
+ if start == end:
74
+ # Leaf node
75
+ if start < len(values):
76
+ self.tree[node] = values[start]
77
+ return
78
+
79
+ mid = (start + end) // 2
80
+ left_child = 2 * node
81
+ right_child = 2 * node + 1
82
+
83
+ # Recursively build left and right subtrees
84
+ self._build(values, left_child, start, mid)
85
+ self._build(values, right_child, mid + 1, end)
86
+
87
+ # Update current node with summary of children
88
+ self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child])
89
+
90
+ def _children(self, node: int) -> list[int]:
91
+ return [2 * node, 2 * node + 1]
92
+
93
+ def _push_lazy(self, node: int, start: int, end: int) -> None:
94
+ """
95
+ Push lazy updates down to children.
96
+
97
+ Args:
98
+ node: Current node index
99
+ start: Start index of the segment
100
+ end: End index of the segment
101
+ """
102
+ lazy_node = self.lazy[node]
103
+ if lazy_node is None:
104
+ return
105
+
106
+ # Apply lazy update to current node
107
+ self.tree[node] = self.update_op(self.tree[node], lazy_node)
108
+
109
+ if start != end: # Not a leaf node
110
+ # Propagate to children
111
+ for child in self._children(node):
112
+ self.lazy[child] = self.update_op(
113
+ _value_or(self.lazy[child], self.identity), lazy_node
114
+ )
115
+
116
+ # Clear the lazy value
117
+ self.lazy[node] = None
118
+
119
+ def _update_range_helper(
120
+ self, node: int, start: int, end: int, left: int, right: int, value: T
121
+ ) -> None:
122
+ """
123
+ Helper method to update a range of values in the segment tree.
124
+
125
+ Args:
126
+ node: Current node index
127
+ start: Start index of the current segment
128
+ end: End index of the current segment
129
+ left: Start index of the range to update
130
+ right: End index of the range to update
131
+ value: Value to apply to the range
132
+ """
133
+ # Push lazy updates before processing this node
134
+ self._push_lazy(node, start, end)
135
+
136
+ # No overlap
137
+ if start > right or end < left:
138
+ return
139
+
140
+ # Complete overlap
141
+ if start >= left and end <= right:
142
+ # Apply update to current node
143
+ self.lazy[node] = value
144
+ self._push_lazy(node, start, end)
145
+ return
146
+
147
+ # Partial overlap, recurse to children
148
+ mid = (start + end) // 2
149
+ left_child = 2 * node
150
+ right_child = 2 * node + 1
151
+
152
+ self._update_range_helper(left_child, start, mid, left, right, value)
153
+ self._update_range_helper(right_child, mid + 1, end, left, right, value)
154
+
155
+ # Update current node based on children
156
+ self.tree[node] = self.summary_op(self.tree[left_child], self.tree[right_child])
157
+
158
+ def _query_range_helper(
159
+ self, node: int, start: int, end: int, left: int, right: int
160
+ ) -> T:
161
+ """
162
+ Helper method to query a range of values in the segment tree.
163
+
164
+ Args:
165
+ node: Current node index
166
+ start: Start index of the current segment
167
+ end: End index of the current segment
168
+ left: Start index of the range to query
169
+ right: End index of the range to query
170
+
171
+ Returns:
172
+ Summary value for the range
173
+ """
174
+ # No overlap
175
+ if start > right or end < left:
176
+ return self.identity
177
+
178
+ # Push lazy updates before processing this node
179
+ self._push_lazy(node, start, end)
180
+
181
+ # Complete overlap
182
+ if start >= left and end <= right:
183
+ return self.tree[node]
184
+
185
+ # Partial overlap, recurse to children
186
+ mid = (start + end) // 2
187
+ left_child = 2 * node
188
+ right_child = 2 * node + 1
189
+
190
+ left_result = self._query_range_helper(left_child, start, mid, left, right)
191
+ right_result = self._query_range_helper(right_child, mid + 1, end, left, right)
192
+
193
+ # Combine results from children
194
+ return self.summary_op(left_result, right_result)
195
+
196
+ def update_range(self, start: int, end: int, value: T) -> None:
197
+ """
198
+ Update a range of values in the segment tree.
199
+
200
+ Args:
201
+ start: Start index of the range to update (inclusive)
202
+ end: End index of the range to update (inclusive)
203
+ value: Value to apply to the range
204
+
205
+ Raises:
206
+ ValueError: If start > end or indices are out of bounds
207
+ """
208
+ if start > end:
209
+ raise ValueError("Start index must be less than or equal to end index")
210
+
211
+ if start < 0 or start >= self.n:
212
+ raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]")
213
+
214
+ if end < 0 or end >= self.n:
215
+ raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]")
216
+
217
+ self._update_range_helper(1, 0, self.n - 1, start, end, value)
218
+
219
+ def summarize_range(self, start: int, end: int) -> T:
220
+ """
221
+ Query a range of values in the segment tree.
222
+
223
+ Args:
224
+ start: Start index of the range to query (inclusive)
225
+ end: End index of the range to query (inclusive)
226
+
227
+ Returns:
228
+ Summary value for the range according to the summary operation
229
+
230
+ Raises:
231
+ ValueError: If start > end or indices are out of bounds
232
+ """
233
+ if start > end:
234
+ raise ValueError("Start index must be less than or equal to end index")
235
+
236
+ if start < 0 or start >= self.n:
237
+ raise ValueError(f"Start index {start} out of bounds [0, {self.n - 1}]")
238
+
239
+ if end < 0 or end >= self.n:
240
+ raise ValueError(f"End index {end} out of bounds [0, {self.n - 1}]")
241
+
242
+ return self._query_range_helper(1, 0, self.n - 1, start, end)
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/simd_kernel_features.py ADDED
@@ -0,0 +1,790 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import dataclasses
5
+ import functools
6
+ import itertools
7
+ import typing
8
+ from typing import Any
9
+
10
+ import sympy
11
+
12
+ import torch
13
+
14
+ from ...utils._ordered_set import OrderedSet
15
+ from ...utils._sympy.functions import FloorDiv, Min, ModularIndexing
16
+ from ...utils._sympy.symbol import make_symbol, SymT
17
+ from .. import ir
18
+ from ..dependencies import Dep, extract_loop_body_with_args, MemoryDep
19
+ from ..runtime.hints import ReductionHint
20
+ from ..runtime.runtime_utils import next_power_of_2
21
+ from ..scheduler import SchedulerNode
22
+ from ..utils import cache_on_self
23
+ from ..virtualized import V
24
+
25
+
26
+ if typing.TYPE_CHECKING:
27
+ from collections.abc import Iterable, Sequence
28
+
29
+ from torch._inductor.tiling_utils import CoalesceVarAnalysis
30
+
31
+
32
+ _INNER_REDUCTION_RATIO = 32
33
+ _SMALL_INNER_REDUCTION_RATIO = 16
34
+ _SMALL_INNER_REDUCTION_MAX_RBLOCK = 512
35
+
36
+
37
+ def tiling_scores_suggest_inner_reduction(
38
+ tiling_scores: dict[str, sympy.Expr], reduction_numel: sympy.Expr
39
+ ) -> bool:
40
+ """Return whether tiling scores justify treating a reduction as inner."""
41
+ sizevars = V.graph.sizevars
42
+ non_reduction_score = sum(
43
+ sizevars.optimization_hint(tiling_scores.get(dim, 0), fallback=0)
44
+ for dim in ("x", "y", "z")
45
+ )
46
+ non_reduction_score = max(non_reduction_score, 1)
47
+ r_score = sizevars.optimization_hint(tiling_scores["r0_"], fallback=0)
48
+ if r_score >= _INNER_REDUCTION_RATIO * non_reduction_score:
49
+ return True
50
+ if r_score < _SMALL_INNER_REDUCTION_RATIO * non_reduction_score:
51
+ return False
52
+
53
+ # Moderate score ratios are useful while persistent configs can keep XBLOCK=8.
54
+ rblock_hint = next_power_of_2(
55
+ max(sizevars.optimization_hint(reduction_numel, fallback=1), 1)
56
+ )
57
+ return rblock_hint <= _SMALL_INNER_REDUCTION_MAX_RBLOCK
58
+
59
+
60
+ class NodeScheduleMarker:
61
+ @staticmethod
62
+ def only_nodes(it: Iterable[NodeScheduleEntry]) -> Iterable[SchedulerNode]:
63
+ for item in it:
64
+ if not (item is DisableReduction or item is EnableReduction):
65
+ yield item # type: ignore[misc]
66
+
67
+ @staticmethod
68
+ def is_reduction() -> bool:
69
+ return False
70
+
71
+
72
+ NodeScheduleEntry = SchedulerNode | type[NodeScheduleMarker]
73
+
74
+
75
+ class DisableReduction(NodeScheduleMarker):
76
+ """
77
+ Marker to invoke `kernel.disable_reduction()`. This closes a
78
+ reduction loop and allows for pointwise ops to occur on the output
79
+ of a reduction.
80
+ """
81
+
82
+
83
+ class EnableReduction(NodeScheduleMarker):
84
+ """
85
+ Marker to end a DisableReduction block.
86
+ """
87
+
88
+ @staticmethod
89
+ def filter(node_schedule: list[NodeScheduleEntry]) -> Iterable[SchedulerNode]:
90
+ """
91
+ Get the nodes from node_schedule skipping those in a
92
+ DisableReduction block.
93
+ """
94
+ disabled = False
95
+ for node in node_schedule:
96
+ if node in (EnableReduction, DisableReduction):
97
+ # Don't tile stuff outside the main reduction loop
98
+ disabled = node is DisableReduction
99
+ elif disabled:
100
+ pass
101
+ else:
102
+ yield node # type: ignore[misc]
103
+
104
+
105
+ class SIMDKernelFeatures:
106
+ """
107
+ An ordered schedule of nodes that will become a single kernel.
108
+ """
109
+
110
+ def __init__(
111
+ self,
112
+ node_schedule: list[NodeScheduleEntry],
113
+ numel: sympy.Expr,
114
+ reduction_numel: sympy.Expr = sympy.S.One,
115
+ coalesce_analysis: CoalesceVarAnalysis | None = None,
116
+ tiling_scores: dict[str, sympy.Expr] | None = None,
117
+ ):
118
+ self.node_schedule = node_schedule
119
+ # numel excludes reduction_numel
120
+ self.numel: sympy.Expr = V.graph.sizevars.simplify(numel)
121
+ self.reduction_numel: sympy.Expr = V.graph.sizevars.simplify(reduction_numel)
122
+ self._stats_cache: dict[tuple[sympy.Expr, ...], MemoryStats] = {}
123
+ self.coalesce_analysis = coalesce_analysis
124
+ self.tiling_scores = tiling_scores
125
+
126
+ def with_tiling_scores(
127
+ self, tiling_scores: dict[str, sympy.Expr] | None
128
+ ) -> SIMDKernelFeatures:
129
+ return SIMDKernelFeatures(
130
+ self.node_schedule,
131
+ self.numel,
132
+ self.reduction_numel,
133
+ self.coalesce_analysis,
134
+ tiling_scores,
135
+ )
136
+
137
+ @cache_on_self
138
+ def is_reduction(self) -> bool:
139
+ return self.reduction_numel != 1
140
+
141
+ @cache_on_self
142
+ def scheduler_nodes(self) -> Iterable[SchedulerNode]:
143
+ return tuple(NodeScheduleMarker.only_nodes(self.node_schedule))
144
+
145
+ def reduction_nodes(self) -> list[SchedulerNode]:
146
+ return [n for n in self.scheduler_nodes() if n.is_reduction()]
147
+
148
+ @cache_on_self
149
+ def strict_sum_reductions(self) -> tuple[ir.Reduction, ...]:
150
+ return tuple(
151
+ node.node.data
152
+ for node in self.reduction_nodes()
153
+ if isinstance(node.node, ir.ComputedBuffer)
154
+ and isinstance(node.node.data, ir.Reduction)
155
+ and node.node.data.strict_sum_rblock is not None
156
+ )
157
+
158
+ def has_strict_sum_multirow_reduction(self) -> bool:
159
+ return any(r.strict_sum_multirow for r in self.strict_sum_reductions())
160
+
161
+ @cache_on_self
162
+ def strict_sum_rblock(self) -> int | None:
163
+ rblocks = OrderedSet(
164
+ reduction.strict_sum_rblock for reduction in self.strict_sum_reductions()
165
+ )
166
+ if not rblocks:
167
+ return None
168
+ if len(rblocks) != 1:
169
+ raise AssertionError(
170
+ f"strict sums require one reduction block size, got {rblocks}"
171
+ )
172
+ return next(iter(rblocks))
173
+
174
+ @cache_on_self
175
+ def buf_accesses(self) -> dict[str, list[Dep]]:
176
+ """only needed for config.benchmark_kernel"""
177
+ buf_accesses = collections.defaultdict(list)
178
+ for node in self.scheduler_nodes():
179
+ for access in node.read_writes.reads | node.read_writes.writes:
180
+ buf_accesses[access.name].append(access)
181
+ return buf_accesses
182
+
183
+ @cache_on_self
184
+ def op_counts(self) -> collections.Counter[str]:
185
+ counts: collections.Counter[str] = collections.Counter()
186
+ for node in self.scheduler_nodes():
187
+ counts.update(node._body.op_counts)
188
+ return counts
189
+
190
+ def contains_op(self, op_name: str) -> bool:
191
+ """True if V.ops.{op_name} is used in node_schedule"""
192
+ return bool(self.op_counts().get(op_name))
193
+
194
+ def get_mutations(self) -> OrderedSet[str]:
195
+ mutations: OrderedSet[str] = OrderedSet()
196
+ for node in self.scheduler_nodes():
197
+ for buf in node.get_outputs():
198
+ mutations.update(buf.get_mutations())
199
+ return mutations
200
+
201
+ @cache_on_self
202
+ def select_index_dtype(self) -> torch.dtype:
203
+ # Gather all used buffer names
204
+ buffer_names: OrderedSet[str] = OrderedSet()
205
+ for node in self.scheduler_nodes():
206
+ buffer_names.update(node.get_buffer_names())
207
+ buffer_names.update(node.used_buffer_names())
208
+ buffers = [V.graph.get_buffer(name) for name in buffer_names]
209
+
210
+ # In theory we can separately check xnumel and rnumel are <= int_max
211
+ # but some indexers do use the full linear index so we need to be
212
+ # conservative here.
213
+ total_numel = self.numel * self.reduction_numel
214
+
215
+ from .simd import SIMDScheduling
216
+
217
+ if SIMDScheduling.can_use_32bit_indexing(total_numel, buffers):
218
+ # Fused address expressions can overflow int32 even when
219
+ # numel/storage_size are within range, so check them directly.
220
+ if self.any_index_expr_overflows_int32():
221
+ return torch.int64
222
+ return torch.int32
223
+ return torch.int64
224
+
225
+ @cache_on_self
226
+ def any_index_expr_overflows_int32(self) -> bool:
227
+ """Return True if any MemoryDep addressing expression can overflow int32.
228
+
229
+ Two complementary checks are applied to each index:
230
+
231
+ - Constant offset: the index evaluated at the origin (every loop
232
+ variable set to 0) must lie within [-2**31, 2**31 - 1]. This is cheap
233
+ and independent of loop-var ranges, so it also covers deps whose sizes
234
+ are symbolic.
235
+ - Variable-scaled bound: the index bounded over the actual iteration
236
+ range of every loop variable must not exceed 2**31 - 1. This catches
237
+ overflow such as the `V * x0` synthesized when unrolled chunked-loop
238
+ slices are stitched into one pointwise kernel (`V` a per-chunk stride,
239
+ `x0` spanning the fused numel); unlike a `numel * max_stride` proxy it
240
+ is exact, since a stride on a size-1 dim multiplies an empty range and
241
+ drops out. Deps with a symbolic loop-var size, or whose bound is
242
+ unknown/indirect (infinite), are skipped here and left to the
243
+ constant-offset and per-buffer storage-size checks.
244
+ """
245
+ from torch.utils._sympy.numbers import int_oo
246
+ from torch.utils._sympy.value_ranges import bound_sympy, ValueRanges
247
+
248
+ int32_max = sympy.Integer(2**31 - 1)
249
+ int32_min = sympy.Integer(-(2**31))
250
+ for node in self.scheduler_nodes():
251
+ for dep in itertools.chain(node.read_writes.reads, node.read_writes.writes):
252
+ if not isinstance(dep, MemoryDep):
253
+ continue
254
+ index = dep.index
255
+ if not isinstance(index, sympy.Expr):
256
+ continue
257
+
258
+ # Constant offset (index at the origin).
259
+ try:
260
+ const_part = index.subs(
261
+ {s: sympy.Integer(0) for s in index.free_symbols}
262
+ )
263
+ if isinstance(const_part, sympy.Expr) and (
264
+ const_part > int32_max or const_part < int32_min
265
+ ):
266
+ return True
267
+ except (ZeroDivisionError, TypeError, ValueError):
268
+ pass
269
+
270
+ # Variable-scaled bound over concrete loop-var ranges. A
271
+ # ValueRanges bound must be concrete, so skip a dep with any
272
+ # symbolic loop-var size.
273
+ sizes = dep.size
274
+ if any(getattr(s, "free_symbols", None) for s in sizes):
275
+ continue
276
+ try:
277
+ var_ranges = {
278
+ var: ValueRanges(0, max(int(size) - 1, 0))
279
+ for var, size in zip(dep.var_names, sizes)
280
+ }
281
+ upper = bound_sympy(index, var_ranges).upper
282
+ if (
283
+ isinstance(upper, sympy.Expr)
284
+ and not upper.has(int_oo, sympy.oo)
285
+ and upper > int32_max
286
+ ):
287
+ return True
288
+ except (ZeroDivisionError, TypeError, ValueError):
289
+ continue
290
+ return False
291
+
292
+ def get_reduction_hint(
293
+ self, tiling_scores: dict[str, sympy.Expr] | None = None
294
+ ) -> ReductionHint:
295
+ if tiling_scores is None:
296
+ tiling_scores = self.tiling_scores
297
+ reductions = self.reduction_nodes()
298
+ if len(reductions) > 0:
299
+ hints = [self.reduction_hint(n) for n in reductions]
300
+ if hints.count(hints[0]) == len(hints):
301
+ reduction_hint_val = hints[0]
302
+ else:
303
+ reduction_hint_val = ReductionHint.DEFAULT
304
+
305
+ if (
306
+ reduction_hint_val == ReductionHint.INNER
307
+ and self.has_non_contiguous_pw_in_reduction_kernel()
308
+ ):
309
+ reduction_hint_val = ReductionHint.DEFAULT
310
+
311
+ # Upgrade DEFAULT to INNER for inner reductions based on tiling scores
312
+ if (
313
+ reduction_hint_val == ReductionHint.DEFAULT
314
+ and tiling_scores is not None
315
+ and "x" in tiling_scores
316
+ and "r0_" in tiling_scores
317
+ ):
318
+ if tiling_scores_suggest_inner_reduction(
319
+ tiling_scores, self.reduction_numel
320
+ ):
321
+ reduction_hint_val = ReductionHint.INNER
322
+ else:
323
+ reduction_hint_val = ReductionHint.DEFAULT
324
+ return reduction_hint_val
325
+
326
+ @cache_on_self
327
+ def buffer_read_counts(self) -> dict[str, int]:
328
+ """Counts how many times each buffer is read within the kernel"""
329
+ read_counts: dict[str, int] = collections.defaultdict(int)
330
+
331
+ for node in self.scheduler_nodes():
332
+ # node.read_writes.reads contains MemoryDep objects for each read
333
+ for read_dep in node.read_writes.reads:
334
+ read_counts[read_dep.name] += 1
335
+
336
+ return dict(read_counts) # Convert defaultdict to regular dict
337
+
338
+ def has_non_contiguous_pw_in_reduction_kernel(self) -> bool:
339
+ pointwise_nodes = [
340
+ n
341
+ for n in self.scheduler_nodes()
342
+ if not n.is_reduction()
343
+ and n.group[1][0] == self.numel * self.reduction_numel
344
+ ]
345
+ for node in pointwise_nodes:
346
+ # An index can be an integer when loading a random seed.
347
+ if not all(
348
+ not isinstance(dep, MemoryDep)
349
+ or dep.is_contiguous()
350
+ or isinstance(dep.index, (sympy.Integer, int))
351
+ or dep.stride1_for_last_dim()
352
+ for dep in itertools.chain(
353
+ node.read_writes.reads, node.read_writes.writes
354
+ )
355
+ ):
356
+ return True
357
+ return False
358
+
359
+ @staticmethod
360
+ def reduction_hint(node: Any) -> ReductionHint:
361
+ if not node.is_reduction():
362
+ raise AssertionError("expected node to be a reduction")
363
+ if node.node.data.reduction_hint != ReductionHint.INNER and all(
364
+ dep.is_contiguous()
365
+ for dep in itertools.chain(node.read_writes.reads, node.read_writes.writes)
366
+ ):
367
+ return ReductionHint.INNER
368
+ else:
369
+ return node.node.data.reduction_hint
370
+
371
+ def memory_stats(
372
+ self, groups_dict: dict[str, sympy.Expr] | None = None
373
+ ) -> MemoryStats:
374
+ """Analysis to generate features that can be used in heuristics"""
375
+ if groups_dict is None:
376
+ groups = (self.numel, self.reduction_numel)
377
+ elif groups_dict.keys() == OrderedSet(["x", "r0_"]):
378
+ groups = (groups_dict["x"], groups_dict["r0_"])
379
+ else:
380
+ raise NotImplementedError(f"groups_dict={groups_dict!r}")
381
+ result = self._stats_cache.get(groups)
382
+ if result is None:
383
+ self._stats_cache[groups] = result = MemoryStats.compute(
384
+ MemoryEstimator(self, groups)
385
+ )
386
+ return result
387
+
388
+
389
+ class MemoryEstimator:
390
+ """
391
+ Estimate various properties of the kernel for use in heuristics.
392
+ We simulate the memory effects of CSE/buffer elimination in codegen.
393
+ """
394
+
395
+ kernel_sizes: tuple[sympy.Expr, ...]
396
+ outside_loop: MemoryEstimate
397
+ loops: list[MemoryEstimate]
398
+ persistent: MemoryEstimate
399
+ symbols: list[sympy.Symbol]
400
+
401
+ def __init__(self, features: SIMDKernelFeatures, groups: Sequence[sympy.Expr]):
402
+ self.features = features
403
+ self.inside_reduction = features.is_reduction()
404
+ self.store_buffer_names: OrderedSet[str] = OrderedSet()
405
+ self.must_keep_buffers: OrderedSet[str] = OrderedSet()
406
+ self.num_reductions_dims = 1
407
+ self.groups = groups
408
+ self.symbols = [make_symbol(SymT.INDEX, i) for i in range(len(groups))]
409
+ # We are doing two estimates simultaneously:
410
+ # 1) the first is a for a non-persistent (aka looped) reduction, using self.outside_loop/self.loops
411
+ # we add an item to loops each corresponding to each reduction loop in the kernel
412
+ # outside_loop is only used for broadcasting or point-wise ops that don't use the reduction dimension
413
+ # 2) the second is for a persistent kernel, using self.persistent
414
+ # persistent kernels don't have loops, so we only have one MemoryEstimate()
415
+ # for point-wise ops the two estimates will be the same, they matter for reductions only
416
+ self.outside_loop = MemoryEstimate()
417
+ self.loops = [MemoryEstimate()]
418
+ self.persistent = MemoryEstimate()
419
+ self.simulate_codegen()
420
+ self.remove_kernel_local()
421
+
422
+ def simulate_codegen(self) -> None:
423
+ from .simd import SIMDKernel
424
+
425
+ kernel_size_outside_loop = (*self.groups[:-1], sympy.S.One)
426
+ kernel_size_inside_loop = tuple(self.groups)
427
+ self.kernel_sizes = kernel_size_inside_loop
428
+
429
+ for node in self.features.node_schedule:
430
+ if node is DisableReduction:
431
+ self.inside_reduction = False
432
+ self.kernel_sizes = kernel_size_outside_loop
433
+ continue
434
+ elif node is EnableReduction:
435
+ self.inside_reduction = True
436
+ self.kernel_sizes = kernel_size_inside_loop
437
+ self.loops.append(MemoryEstimate())
438
+ continue
439
+ if not isinstance(node, SchedulerNode):
440
+ raise AssertionError(f"expected SchedulerNode, got {type(node)}")
441
+ rw = extract_loop_body_with_args(
442
+ node._body,
443
+ SIMDKernel.map_kernel_groups_to_node_sizes(
444
+ self.kernel_sizes, node.get_ranges(), self.set_ranges
445
+ ),
446
+ dict(zip(self.symbols, self.kernel_sizes)),
447
+ )
448
+
449
+ for dep in rw._reads:
450
+ if not isinstance(dep, MemoryDep):
451
+ continue
452
+ dep = dep.simplify_with_ranges()
453
+ if not self.persistent.writes.get(dep.name): # cache miss?
454
+ self.persistent.reads[dep.name].add(dep)
455
+ # the cache behavior of looped kernels is more complex than the persistent case above
456
+ # some operations are lifted outside the loop (if they don't use the reduction dimension)
457
+ # other operations are inside the loop, and can only be reused within the same loop
458
+ if not (
459
+ self.outside_loop.writes.get(dep.name)
460
+ or self.loops[-1].writes.get(dep.name)
461
+ ):
462
+ self.scope(dep).reads[dep.name].add(dep)
463
+ if dep.name in self.store_buffer_names and self.loops[-1].reads.get(
464
+ dep.name
465
+ ):
466
+ self.must_keep_buffers.add(dep.name)
467
+
468
+ for dep in rw._writes:
469
+ if not isinstance(dep, MemoryDep):
470
+ continue
471
+ dep = dep.simplify_with_ranges()
472
+ self.store_buffer_names.add(dep.name)
473
+ self.persistent.writes[dep.name].add(dep)
474
+ self.scope(dep).writes[dep.name].add(dep)
475
+
476
+ def remove_kernel_local(self) -> None:
477
+ # Remove any kernel-local buffers
478
+ fused_node_names = OrderedSet(
479
+ [n.get_name() for n in self.features.scheduler_nodes()]
480
+ )
481
+ for name in self.store_buffer_names:
482
+ if not self.persistent.reads.get(
483
+ name
484
+ ) and V.graph.scheduler.can_buffer_be_removed_through_fusion(
485
+ name, fused_node_names
486
+ ):
487
+ self.persistent.remove(name)
488
+ if name not in self.must_keep_buffers:
489
+ # we can also remove this from the looped kernel
490
+ self.outside_loop.remove(name)
491
+ for loop in self.loops:
492
+ loop.remove(name)
493
+
494
+ if not self.loops[-1]:
495
+ self.loops.pop() # for pointwise ops
496
+
497
+ def scope(self, dep: MemoryDep) -> MemoryEstimate:
498
+ """Determine how a read/write should be categorized"""
499
+ if self.inside_reduction and (
500
+ self.has_reduction_var(dep.index) or dep.is_indirect()
501
+ ):
502
+ return self.loops[-1]
503
+ return self.outside_loop
504
+
505
+ def has_reduction_var(self, index: sympy.Expr) -> bool:
506
+ for sym in self.symbols[-self.num_reductions_dims :]:
507
+ if isinstance(sym, sympy.Symbol) and sym in index.free_symbols:
508
+ return True
509
+ return False
510
+
511
+ def set_ranges(self, *lengths: list[list[sympy.Expr]]) -> list[list[sympy.Expr]]:
512
+ if len(self.kernel_sizes) != len(lengths):
513
+ raise AssertionError(
514
+ f"expected len(kernel_sizes) == len(lengths), got "
515
+ f"{len(self.kernel_sizes)} != {len(lengths)}"
516
+ )
517
+ return [
518
+ self.make_flat_range(sym, numel, length)
519
+ for sym, numel, length in zip(self.symbols, self.kernel_sizes, lengths)
520
+ ]
521
+
522
+ @staticmethod
523
+ def make_flat_range(
524
+ sym: sympy.Symbol, numel: sympy.Expr, lengths: list[sympy.Expr]
525
+ ) -> list[sympy.Expr]:
526
+ if len(lengths) == 1 and numel == lengths[0]:
527
+ return [sym]
528
+ divisor = sympy.S.One
529
+ itervars = []
530
+ for length in reversed(lengths):
531
+ if V.graph.sizevars.statically_known_equals(divisor * length, numel):
532
+ expr = FloorDiv(sym, divisor)
533
+ else:
534
+ expr = ModularIndexing(sym, divisor, length)
535
+ itervars.append(expr)
536
+ divisor = divisor * length
537
+ return [*reversed(itervars)]
538
+
539
+
540
+ @dataclasses.dataclass
541
+ class MemoryEstimate:
542
+ """Tracks the memory usage of a single loop in the generated kernel"""
543
+
544
+ reads: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
545
+ default_factory=functools.partial(collections.defaultdict, OrderedSet)
546
+ )
547
+ writes: dict[str, OrderedSet[MemoryDep]] = dataclasses.field(
548
+ default_factory=functools.partial(collections.defaultdict, OrderedSet)
549
+ )
550
+
551
+ def remove(self, name: str) -> None:
552
+ self.reads.pop(name, None)
553
+ self.writes.pop(name, None)
554
+
555
+ def __bool__(self) -> bool:
556
+ return bool(self.reads or self.writes)
557
+
558
+ def __repr__(self) -> str:
559
+ return f"""MemoryEstimate(
560
+ reads={[*itertools.chain.from_iterable(self.reads.values())]!r},
561
+ writes={[*itertools.chain.from_iterable(self.writes.values())]!r}
562
+ )"""
563
+
564
+
565
+ @dataclasses.dataclass
566
+ class StatsForDim:
567
+ """Memory usage stats for a block dimension in the generated kernel (different from user dimensions)"""
568
+
569
+ # the number of load/store ops
570
+ count_per_thread_contiguous: int = 0
571
+ count_per_thread_broadcast: int = 0
572
+ count_per_thread_non_contiguous: int = 0 # excludes broadcast
573
+
574
+ # total bytes in each load/store op for a single element
575
+ bytes_per_thread_contiguous: int = 0
576
+ bytes_per_thread_broadcast: int = 0
577
+ bytes_per_thread_non_contiguous: int = 0 # excludes broadcast
578
+
579
+ # total bytes read by entire kernel
580
+ bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero
581
+ bytes_non_contiguous: sympy.Expr = sympy.S.Zero
582
+
583
+ def __add__(self, other: typing.Self) -> StatsForDim:
584
+ return StatsForDim(
585
+ count_per_thread_contiguous=self.count_per_thread_contiguous
586
+ + other.count_per_thread_contiguous,
587
+ count_per_thread_broadcast=self.count_per_thread_broadcast
588
+ + other.count_per_thread_broadcast,
589
+ count_per_thread_non_contiguous=self.count_per_thread_non_contiguous
590
+ + other.count_per_thread_non_contiguous,
591
+ bytes_per_thread_contiguous=self.bytes_per_thread_contiguous
592
+ + other.bytes_per_thread_contiguous,
593
+ bytes_per_thread_broadcast=self.bytes_per_thread_broadcast
594
+ + other.bytes_per_thread_broadcast,
595
+ bytes_per_thread_non_contiguous=self.bytes_per_thread_non_contiguous
596
+ + other.bytes_per_thread_non_contiguous,
597
+ bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast
598
+ + other.bytes_contiguous_or_broadcast,
599
+ bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous,
600
+ )
601
+
602
+ @property
603
+ def count_per_thread(self) -> int:
604
+ return (
605
+ self.count_per_thread_contiguous
606
+ + self.count_per_thread_broadcast
607
+ + self.count_per_thread_non_contiguous
608
+ )
609
+
610
+ @property
611
+ def bytes_per_thread(self) -> int:
612
+ return (
613
+ self.bytes_per_thread_contiguous
614
+ + self.bytes_per_thread_broadcast
615
+ + self.bytes_per_thread_non_contiguous
616
+ )
617
+
618
+ @property
619
+ def bytes(self) -> sympy.Expr:
620
+ return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous
621
+
622
+ @property
623
+ def contiguous_score(self) -> float:
624
+ return 1.0 - self.count_per_thread_non_contiguous / max(
625
+ self.count_per_thread, 1
626
+ )
627
+
628
+
629
+ @dataclasses.dataclass
630
+ class StatsForLoop:
631
+ """Memory usage stats for single loop in the generated kernel"""
632
+
633
+ # load/store ops
634
+ count_per_thread: int = 0
635
+ bytes_per_thread: int = 0
636
+
637
+ def __add__(self, other: typing.Self) -> StatsForLoop:
638
+ return StatsForLoop(
639
+ count_per_thread=self.count_per_thread + other.count_per_thread,
640
+ bytes_per_thread=self.bytes_per_thread + other.bytes_per_thread,
641
+ )
642
+
643
+
644
+ @dataclasses.dataclass
645
+ class StatsForReadsOrWrites:
646
+ """Memory usage stats that are collected for reads/writes/both"""
647
+
648
+ dim: list[StatsForDim]
649
+ loop: list[StatsForLoop]
650
+ # total bytes contiguous in any dimension
651
+ bytes_contiguous_or_broadcast: sympy.Expr = sympy.S.Zero
652
+ bytes_non_contiguous: sympy.Expr = sympy.S.Zero
653
+
654
+ def __add__(self, other: typing.Self) -> StatsForReadsOrWrites:
655
+ if len(self.dim) != len(other.dim):
656
+ raise AssertionError(
657
+ f"expected len(self.dim) == len(other.dim), got "
658
+ f"{len(self.dim)} != {len(other.dim)}"
659
+ )
660
+ if len(self.loop) != len(other.loop):
661
+ raise AssertionError(
662
+ f"expected len(self.loop) == len(other.loop), got "
663
+ f"{len(self.loop)} != {len(other.loop)}"
664
+ )
665
+ return StatsForReadsOrWrites(
666
+ dim=[a + b for a, b in zip(self.dim, other.dim)],
667
+ loop=[a + b for a, b in zip(self.loop, other.loop)],
668
+ bytes_contiguous_or_broadcast=self.bytes_contiguous_or_broadcast
669
+ + self.bytes_contiguous_or_broadcast,
670
+ bytes_non_contiguous=self.bytes_non_contiguous + other.bytes_non_contiguous,
671
+ )
672
+
673
+ @property
674
+ def count_per_thread(self) -> int:
675
+ return self.dim[0].count_per_thread
676
+
677
+ @property
678
+ def bytes_per_thread(self) -> int:
679
+ return self.dim[0].bytes_per_thread
680
+
681
+ @property
682
+ def bytes(self) -> sympy.Expr:
683
+ return self.bytes_contiguous_or_broadcast + self.bytes_non_contiguous
684
+
685
+ @classmethod
686
+ def compute(
687
+ cls,
688
+ loop_deps: list[dict[str, OrderedSet[MemoryDep]]],
689
+ index_symbols: list[sympy.Symbol],
690
+ ) -> typing.Self:
691
+ ndim = len(index_symbols)
692
+ result = cls(dim := [StatsForDim() for _ in range(ndim)], [])
693
+ for dep_group in loop_deps:
694
+ result.loop.append(loop_stats := StatsForLoop())
695
+ for name, deps in dep_group.items():
696
+ if not deps:
697
+ raise AssertionError(f"expected non-empty deps for {name}")
698
+ contiguous_or_broadcast = [True] * ndim
699
+ numel = sympy.S.Zero
700
+ itemsize = V.graph.get_dtype(name).itemsize
701
+ loop_stats.count_per_thread += len(deps)
702
+ loop_stats.bytes_per_thread += itemsize * len(deps)
703
+ for dep in deps:
704
+ strides: list[sympy.Expr] = V.graph.sizevars.stride_vars(
705
+ dep.index, index_symbols
706
+ )
707
+ for i in range(ndim):
708
+ if V.graph.sizevars.statically_known_equals(strides[i], 1):
709
+ dim[i].count_per_thread_contiguous += 1
710
+ dim[i].bytes_per_thread_contiguous += itemsize
711
+ elif (
712
+ V.graph.sizevars.statically_known_equals(strides[i], 0)
713
+ and not dep.is_indirect()
714
+ ):
715
+ dim[i].count_per_thread_broadcast += 1
716
+ dim[i].bytes_per_thread_broadcast += itemsize
717
+ else:
718
+ dim[i].count_per_thread_non_contiguous += 1
719
+ dim[i].bytes_per_thread_non_contiguous += itemsize
720
+ contiguous_or_broadcast[i] = False
721
+ numel += dep.get_numel()
722
+ if len(deps) > 1:
723
+ # can't read more elements than exist in the buffer
724
+ numel = Min(numel, V.graph.get_numel(name))
725
+ nbytes = numel * itemsize
726
+ for i in range(ndim):
727
+ if contiguous_or_broadcast[i]:
728
+ dim[i].bytes_contiguous_or_broadcast += nbytes
729
+ else:
730
+ dim[i].bytes_non_contiguous += nbytes
731
+ if any(contiguous_or_broadcast):
732
+ result.bytes_contiguous_or_broadcast += nbytes
733
+ else:
734
+ result.bytes_non_contiguous += nbytes
735
+ if len(result.loop) > 1:
736
+ # the first loop represent the "outside of the loop" compute which could be long lived
737
+ result.loop = [result.loop[0] + x for x in result.loop[1:]]
738
+ return result
739
+
740
+
741
+ @dataclasses.dataclass
742
+ class StatsForKernelType:
743
+ """Memory usage stats that are collected for both persistent and looped kernels"""
744
+
745
+ reads: StatsForReadsOrWrites
746
+ writes: StatsForReadsOrWrites
747
+ memory: StatsForReadsOrWrites
748
+
749
+ @classmethod
750
+ def compute(
751
+ cls, loops: list[MemoryEstimate], estimator: MemoryEstimator
752
+ ) -> typing.Self:
753
+ reads = StatsForReadsOrWrites.compute(
754
+ [loop.reads for loop in loops], estimator.symbols
755
+ )
756
+ writes = StatsForReadsOrWrites.compute(
757
+ [loop.writes for loop in loops], estimator.symbols
758
+ )
759
+ return cls(
760
+ reads=reads,
761
+ writes=writes,
762
+ memory=reads + writes,
763
+ )
764
+
765
+
766
+ @dataclasses.dataclass
767
+ class MemoryStats:
768
+ """Memory usage stats collected for each generated kernel"""
769
+
770
+ persistent: StatsForKernelType
771
+ looped: StatsForKernelType
772
+
773
+ def get(self, persistent: bool) -> StatsForKernelType:
774
+ return self.persistent if persistent else self.looped
775
+
776
+ @classmethod
777
+ def compute(cls, estimator: MemoryEstimator) -> typing.Self:
778
+ persistent = StatsForKernelType.compute([estimator.persistent], estimator)
779
+ if len(estimator.loops) == 1 and not (
780
+ estimator.outside_loop and estimator.loops[0]
781
+ ):
782
+ looped = persistent # loops/persistent is the same in this common case
783
+ else:
784
+ looped = StatsForKernelType.compute(
785
+ [estimator.outside_loop, *estimator.loops], estimator
786
+ )
787
+ return cls(
788
+ persistent=persistent,
789
+ looped=looped,
790
+ )
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/subgraph.py ADDED
@@ -0,0 +1,615 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ import functools
3
+ import itertools
4
+ import logging
5
+ from collections.abc import Callable
6
+ from typing import Any
7
+
8
+ import sympy
9
+
10
+ import torch
11
+ import torch._inductor.config as config
12
+ from torch._dynamo.utils import counters
13
+ from torch._inductor import ir
14
+ from torch._inductor.autotune_process import (
15
+ SubgraphCPUBenchmarkRequest,
16
+ SubgraphGPUBenchmarkRequest,
17
+ TensorMeta,
18
+ )
19
+ from torch._inductor.codegen.common import KernelTemplate
20
+ from torch._inductor.ir import (
21
+ Buffer,
22
+ FixedLayout,
23
+ get_free_symbols,
24
+ get_symbolic_inputs,
25
+ gm_original_output_strides,
26
+ ir_node_to_tensor,
27
+ Layout,
28
+ )
29
+ from torch._inductor.runtime.benchmarking import benchmarker
30
+ from torch._inductor.utils import do_bench_using_profiling
31
+ from torch._inductor.virtualized import V
32
+ from torch.utils._ordered_set import OrderedSet
33
+
34
+
35
+ log = logging.getLogger(__name__)
36
+
37
+
38
+ def inline_subgraph_to_ir_nodes(
39
+ gm: torch.fx.GraphModule, inputs: list[Any], name: str
40
+ ) -> Any:
41
+ """Inline a subgraph by converting its FX operations to individual IR nodes.
42
+
43
+ This converts a subgraph to multiple ComputedBuffer nodes (fusable),
44
+ enabling epilogue fusion with subsequent operations.
45
+
46
+ Returns:
47
+ TensorBox containing the final operation result as individual IR nodes
48
+ """
49
+ from torch._inductor.lowering import process_subgraph_nodes
50
+
51
+ # Temporarily switch V.graph.module to subgraph during processing; restore to prevent IR nodes added to wrong graph
52
+ original_module = V.graph.module
53
+ try:
54
+ V.graph.module = gm
55
+ return process_subgraph_nodes(gm, inputs)
56
+ finally:
57
+ V.graph.module = original_module
58
+
59
+
60
+ class SubgraphChoiceCaller(ir.ChoiceCaller):
61
+ """
62
+ Represents a Subgraph Autotuning choice, and the subgraph can be any arbitrary
63
+ GraphModule. Compiles the Subgraph down to a module for benchmarking.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ name: str,
69
+ input_nodes: list[Buffer],
70
+ layout: Layout,
71
+ description: str,
72
+ make_fx_graph: Callable[..., Any],
73
+ input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None,
74
+ ) -> None:
75
+ super().__init__(name, input_nodes, layout, description)
76
+
77
+ # Create inputs for tracing and benchmarking:
78
+ # - trace_inputs: Always use symbolic inputs for tracing so the graph works
79
+ # for any size at runtime. This correctly captures shape-dependent operations
80
+ # like x * x.shape[0].
81
+ # - benchmark_inputs: Use input_gen_fns if provided (for range-specific benchmarks)
82
+ # or concrete inputs from ir_node_to_tensor with guard_shape=False.
83
+ trace_inputs = []
84
+ self.benchmark_inputs = []
85
+ with V.fake_mode:
86
+ for i, inp in enumerate(self.input_nodes):
87
+ # Here there will be no unbacked symbols, as SubgraphBuffer does not support them
88
+ if len(get_free_symbols(inp.get_size(), unbacked_only=True)) != 0:
89
+ raise AssertionError("expected no unbacked symbols in input size")
90
+ if len(get_free_symbols(inp.get_stride(), unbacked_only=True)) != 0:
91
+ raise AssertionError("expected no unbacked symbols in input stride")
92
+
93
+ inp.data.freeze_layout() # type: ignore[attr-defined]
94
+
95
+ # Always use symbolic inputs for tracing
96
+ trace_inputs.append(ir_node_to_tensor(inp))
97
+
98
+ # Use input_gen_fn for benchmarking if provided, otherwise concrete sizes
99
+ if input_gen_fns is not None and i in input_gen_fns:
100
+ self.benchmark_inputs.append(input_gen_fns[i](inp))
101
+ else:
102
+ self.benchmark_inputs.append(
103
+ ir_node_to_tensor(inp, replace_symbols_with_hints=True)
104
+ )
105
+
106
+ # Trace with symbolic inputs for guard detection
107
+ self.gm = make_fx_graph(*trace_inputs)
108
+ gm_original_output_strides(self.gm)
109
+ # Store symbolic inputs for sym_input computation
110
+ self.example_inputs = trace_inputs
111
+
112
+ self.sym_inputs = get_symbolic_inputs(self.input_nodes)
113
+ self.sym_input_values = self._compute_sym_input_values()
114
+
115
+ # Cached decomposition info for range-based dispatch (set via cache_decomposition)
116
+ self.decomposition: Callable[..., Any] | None = None
117
+ self.decomposition_kwargs: dict[str, Any] = {}
118
+ # Config patches to apply during kernel codegen (e.g., coordinate_descent_tuning)
119
+ self.config_patches: dict[str, Any] = {}
120
+ # Cache compiled module to avoid recompiling on every benchmark call
121
+ self._compiled_module: Any = None
122
+ # Cache benchmark request for async autotuning
123
+ self._bmreq: (
124
+ SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest | None
125
+ ) = None
126
+
127
+ # Pre-compile only if using async pipelined autotuning
128
+ # Must happen in __init__ because compilation requires virtualized context (V.graph, V.debug)
129
+ if config.pipeline_max_autotune_gemm:
130
+ with V.fake_mode:
131
+ self._compiled_module = self._compile_for_benchmarking()
132
+ self._bmreq = self._create_benchmark_request()
133
+
134
+ def _compute_sym_input_values(self) -> list[int]:
135
+ """Extract concrete dimension values for sym_inputs from benchmark_inputs.
136
+
137
+ The compiled module expects symbolic dimension values as runtime arguments.
138
+ This maps each symbolic variable to its concrete value from the benchmark tensors.
139
+ Used for range based autotuning.
140
+ """
141
+ sym_input_names = OrderedSet(
142
+ [s.name for s in self.sym_inputs if hasattr(s, "name")]
143
+ )
144
+
145
+ # Build mapping: symbolic dimension name -> concrete value
146
+ sym_name_to_value: dict[str, int] = {}
147
+ for inp_node, benchmark_inp in zip(self.input_nodes, self.benchmark_inputs):
148
+ if isinstance(benchmark_inp, torch.Tensor):
149
+ for sym_dim, actual_dim in zip(
150
+ inp_node.get_size(), benchmark_inp.shape
151
+ ):
152
+ if isinstance(sym_dim, sympy.Symbol):
153
+ sym_name_to_value[sym_dim.name] = int(actual_dim)
154
+ elif str(sym_dim) in sym_input_names:
155
+ sym_name_to_value[str(sym_dim)] = int(actual_dim)
156
+
157
+ result = []
158
+ for sym_var in self.sym_inputs:
159
+ if isinstance(sym_var, sympy.Symbol) and sym_var.name in sym_name_to_value:
160
+ result.append(sym_name_to_value[sym_var.name])
161
+ else:
162
+ hint = V.graph.sizevars.shape_env.optimization_hint(sym_var, fallback=1)
163
+ result.append(int(hint))
164
+ return result
165
+
166
+ def cache_decomposition(
167
+ self, decomposition: Callable[..., Any], kwargs: dict[str, Any]
168
+ ) -> None:
169
+ """Cache decomposition function and kwargs for range-based dispatch lookup."""
170
+ self.decomposition = decomposition
171
+ self.decomposition_kwargs = kwargs
172
+
173
+ def __str__(self) -> str:
174
+ return f"SubgraphCaller({self.name})"
175
+
176
+ def _compile_for_benchmarking(self) -> Any:
177
+ """Compile the subgraph for benchmarking, returns the compiled module."""
178
+ from torch._inductor.graph import GraphLowering
179
+
180
+ safe_name = self.name.replace("::", "_").replace(".", "_")
181
+
182
+ # Symbolic inputs produce code with symbolic sizes resolved at runtime
183
+ # via sym_input_values. Without symbols (static shapes), compile with
184
+ # benchmark_inputs whose sizes match the actual benchmark tensors.
185
+ compile_inputs = (
186
+ self.example_inputs if self.sym_inputs else self.benchmark_inputs
187
+ )
188
+ log.debug("Benchmark compile %s: sym_inputs=%s", self.name, self.sym_inputs)
189
+
190
+ if self.gm is None:
191
+ raise AssertionError("expected self.gm to be set")
192
+ bm_graph_lowering = GraphLowering(
193
+ gm=self.gm,
194
+ example_inputs=compile_inputs,
195
+ shape_env=V.graph._shape_env,
196
+ cpp_wrapper=V.graph.cpp_wrapper,
197
+ aot_mode=V.graph.aot_mode,
198
+ extern_node_serializer=V.graph.extern_node_serializer,
199
+ is_inference=V.graph.is_inference,
200
+ is_backward=V.graph.is_backward,
201
+ name=f"benchmark_{safe_name}",
202
+ )
203
+
204
+ for sym_inp in self.sym_inputs:
205
+ bm_graph_lowering.graph_inputs[sym_inp.name] = sym_inp
206
+ bm_graph_lowering.graph_input_names.append(sym_inp.name)
207
+
208
+ with V.set_graph_handler(bm_graph_lowering):
209
+ # Apply config_patches during benchmarking (e.g., coordinate_descent_tuning)
210
+ # Also disable max_autotune to avoid nested autotuning
211
+ benchmark_config: dict[str, Any] = {
212
+ "max_autotune": False,
213
+ "max_autotune_gemm": False,
214
+ "max_autotune_gemm_backends": "ATEN",
215
+ "benchmark_fusion": False,
216
+ "pipeline_max_autotune_gemm": False,
217
+ **self.config_patches,
218
+ }
219
+ with config.patch(benchmark_config):
220
+ bm_graph_lowering.run(*compile_inputs)
221
+ return bm_graph_lowering.compile_to_module()
222
+
223
+ def _create_benchmark_request(
224
+ self,
225
+ ) -> SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest:
226
+ """Create a benchmark request for async autotuning."""
227
+ if self._compiled_module is None:
228
+ raise AssertionError(
229
+ "Module must be compiled before creating benchmark request"
230
+ )
231
+ input_tensor_meta = TensorMeta.from_irnodes(self.input_nodes)
232
+ output_tensor_meta = TensorMeta.from_irnodes(self.layout)
233
+
234
+ if self.layout.device.type == "cpu":
235
+ bmreq_cls = SubgraphCPUBenchmarkRequest
236
+ else:
237
+ bmreq_cls = SubgraphGPUBenchmarkRequest
238
+
239
+ return bmreq_cls(
240
+ kernel_name=self.name,
241
+ input_tensor_meta=input_tensor_meta,
242
+ output_tensor_meta=output_tensor_meta,
243
+ extra_args=tuple(),
244
+ module_path=self._compiled_module.__file__,
245
+ module_cache_key=self._compiled_module.key,
246
+ sym_input_values=self.sym_input_values,
247
+ )
248
+
249
+ @property
250
+ def bmreq(
251
+ self,
252
+ ) -> SubgraphGPUBenchmarkRequest | SubgraphCPUBenchmarkRequest:
253
+ """Benchmark request for async autotuning. Pre-compiled when pipeline_max_autotune_gemm is enabled."""
254
+ if self._bmreq is None:
255
+ raise AssertionError(
256
+ "bmreq accessed but pipeline_max_autotune_gemm was not enabled during __init__"
257
+ )
258
+ return self._bmreq
259
+
260
+ def _ensure_compiled(self) -> None:
261
+ """Ensure the module is compiled. Used for lazy compilation in non-async path."""
262
+ if self._compiled_module is None:
263
+ self._compiled_module = self._compile_for_benchmarking()
264
+
265
+ def benchmark(self, *args: list[Any], out: torch.Tensor) -> float:
266
+ """Regular benchmarking: compile if needed, then use benchmarker."""
267
+ self._ensure_compiled()
268
+ bm_func = self._compiled_module.call
269
+ sym_inputs = self.sym_input_values
270
+
271
+ def fn() -> Any:
272
+ return bm_func([*sym_inputs, *args])
273
+
274
+ if self._benchmark_with_cudagraphs:
275
+ return benchmarker.benchmark_gpu_with_cuda_graph(fn)
276
+
277
+ if config.profile_bandwidth_with_do_bench_using_profiling:
278
+ return do_bench_using_profiling(fn)
279
+ return benchmarker.benchmark(
280
+ fn,
281
+ device=benchmarker.infer_device(*sym_inputs, *args),
282
+ )
283
+
284
+ def benchmark_collective(self, *args: list[Any], out: torch.Tensor) -> None:
285
+ """Run once for collective benchmarking (barrier sync handled by caller)."""
286
+ self._ensure_compiled()
287
+ self._compiled_module.call([*self.sym_input_values, *args])
288
+
289
+ def hash_key(self) -> str:
290
+ if self.gm is None:
291
+ raise AssertionError("expected self.gm to be set")
292
+ return "-".join(
293
+ [
294
+ self.name.rsplit("_", 1)[0],
295
+ *[str(inp.get_size()) for inp in self.input_nodes],
296
+ *[str(inp.get_stride()) for inp in self.input_nodes],
297
+ str(self.gm.graph),
298
+ ]
299
+ )
300
+
301
+ def output_node(self) -> ir.TensorBox:
302
+ if self.gm is None:
303
+ raise AssertionError("expected self.gm to be set")
304
+ return ir.TensorBox.create(
305
+ ir.SubgraphBuffer(
306
+ layout=self.layout,
307
+ input_nodes=self.input_nodes,
308
+ gm=self.gm,
309
+ example_inputs=self.example_inputs,
310
+ subgraph_name=self.name,
311
+ config_patches=self.config_patches if self.config_patches else None,
312
+ )
313
+ )
314
+
315
+ def info_dict(self) -> dict[str, Any]:
316
+ """Information returned here is logged to the autotune log file when that is enabled."""
317
+ return {
318
+ "backend": "subgraph",
319
+ "kernel_name": self.name,
320
+ }
321
+
322
+ def autoheuristic_id(self) -> str:
323
+ return f"subgraph_{self.name}"
324
+
325
+
326
+ class SubgraphTemplate(KernelTemplate):
327
+ """
328
+ A template for subgraph evaluation to be used in autotuning.
329
+
330
+ This class allows creating customized subgraphs that can be appended
331
+ as choices during the autotuning process, enabling the selection of
332
+ optimal implementations for complex operations.
333
+ """
334
+
335
+ index_counter = itertools.count()
336
+
337
+ def __init__(
338
+ self,
339
+ name: str,
340
+ ):
341
+ """
342
+ Initialize a subgraph template.
343
+
344
+ Args:
345
+ name: The name of this template
346
+ graph: The FX graph
347
+ """
348
+ super().__init__(name=name)
349
+
350
+ def generate( # type: ignore[override]
351
+ self,
352
+ name: str,
353
+ input_nodes: list[Buffer],
354
+ layout: Layout,
355
+ make_fx_graph: Callable[..., Any],
356
+ description: str = "",
357
+ input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None,
358
+ **kwargs: Any,
359
+ ) -> SubgraphChoiceCaller:
360
+ """
361
+ Generate a SubgraphChoiceCaller instance for autotuning.
362
+
363
+ Args:
364
+ name: The name for this subgraph choice
365
+ input_nodes: List of input nodes to the subgraph
366
+ layout: Memory layout information for the output
367
+ make_fx_graph: Callable that creates the FX graph for this subgraph
368
+ description: Optional description of this choice
369
+ input_gen_fns: Optional dict mapping input indices to tensor generators
370
+ **kwargs: Additional keyword arguments
371
+
372
+ Returns:
373
+ SubgraphChoiceCaller: A callable object that can be used for autotuning
374
+ """
375
+
376
+ return SubgraphChoiceCaller(
377
+ name=f"{name}_{next(SubgraphTemplate.index_counter)}",
378
+ input_nodes=input_nodes,
379
+ layout=layout,
380
+ description=description,
381
+ make_fx_graph=make_fx_graph,
382
+ input_gen_fns=input_gen_fns,
383
+ )
384
+
385
+ def generate_custom_op_choices(
386
+ self,
387
+ name: str,
388
+ decompositions: list[Callable[..., Any]],
389
+ input_nodes: list[Buffer],
390
+ non_tensor_args: list[dict[str, Any]],
391
+ default_impl: Callable[..., Any] | None = None,
392
+ input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None,
393
+ config_patches_list: list[dict[str, Any]] | None = None,
394
+ ) -> list[SubgraphChoiceCaller]:
395
+ """
396
+ Generate multiple SubgraphChoiceCaller instances for custom op autotuning.
397
+
398
+ This method extends SubgraphTemplate to support custom op decompositions,
399
+ allowing multiple implementations to compete in autotuning.
400
+
401
+ Args:
402
+ name: Base name for the choices
403
+ decompositions: List of decomposition functions to compete in autotuning
404
+ input_nodes: List of tensor inputs. All tensor arguments must be passed here.
405
+ non_tensor_args: List of non-tensor kwargs only, one dict per corresponding decomposition.
406
+ default_impl: Default implementation for layout inference
407
+ input_gen_fns: Optional dict mapping input indices to tensor generators
408
+ config_patches_list: Optional list of config patches per decomposition
409
+
410
+ Returns:
411
+ List of SubgraphChoiceCaller instances for autotuning
412
+ """
413
+ if not decompositions:
414
+ return []
415
+
416
+ if len(decompositions) != len(non_tensor_args):
417
+ raise AssertionError(
418
+ f"decompositions and non_tensor_args must have same length, "
419
+ f"got {len(decompositions)} decompositions and {len(non_tensor_args)} kwargs"
420
+ )
421
+
422
+ # Default to empty config_patches if not provided
423
+ if config_patches_list is None:
424
+ config_patches_list = [{} for _ in decompositions]
425
+
426
+ # Infer layouts and ensure layout consistency for fair autotuning comparison
427
+ layouts = [
428
+ self._infer_custom_op_layout(
429
+ input_nodes, decomp, kwargs, default_impl, input_gen_fns
430
+ )
431
+ for decomp, kwargs in zip(decompositions, non_tensor_args)
432
+ ]
433
+
434
+ # Validate all decompositions produce equivalent layouts for fair comparison
435
+ self._validate_layout_equivalence(name, decompositions, layouts)
436
+ layout = layouts[0] # All layouts are now validated to be equivalent
437
+
438
+ choices: list[SubgraphChoiceCaller] = []
439
+ for decomp, decomp_kwargs, config_patches in zip(
440
+ decompositions, non_tensor_args, config_patches_list
441
+ ):
442
+ # Create make_fx_graph function for this decomposition
443
+ # Uses error_on_new_guards to detect impls that add guards
444
+ from torch.fx.experimental.symbolic_shapes import _ShapeEnvGuardError
445
+
446
+ def make_fx_graph(
447
+ *args: Any,
448
+ decomp: Callable[..., Any] = decomp,
449
+ decomp_kwargs: dict[str, Any] = decomp_kwargs,
450
+ ) -> Any:
451
+ # decomp_kwargs contains all merged parameters: CustomOpConfig params + runtime kwargs
452
+
453
+ from torch.fx.experimental.proxy_tensor import make_fx
454
+
455
+ from ..decomposition import select_decomp_table
456
+
457
+ decomposition_table = select_decomp_table()
458
+ shape_env = V.fake_mode.shape_env
459
+
460
+ # Use error_on_new_guards to detect impls that add guards during tracing
461
+ guard_ctx = (
462
+ shape_env.error_on_new_guards()
463
+ if shape_env is not None
464
+ else contextlib.nullcontext()
465
+ )
466
+ with guard_ctx:
467
+ return make_fx(
468
+ functools.partial(decomp, **decomp_kwargs),
469
+ decomposition_table=decomposition_table,
470
+ tracing_mode="symbolic",
471
+ )(*args)
472
+
473
+ # Generate descriptive name for this variant
474
+ variant_name = self._generate_variant_name(decomp, decomp_kwargs)
475
+
476
+ # Try to create choice; skip if it adds guards
477
+ try:
478
+ choice = self.generate(
479
+ name=f"{name}_{variant_name}",
480
+ input_nodes=input_nodes,
481
+ layout=layout,
482
+ make_fx_graph=make_fx_graph,
483
+ description=f"CustomOp {decomp.__name__}",
484
+ input_gen_fns=input_gen_fns,
485
+ )
486
+ except _ShapeEnvGuardError:
487
+ log.info(
488
+ "Skipping decomposition %s: adds guards during tracing",
489
+ decomp.__name__,
490
+ )
491
+ counters["inductor"]["custom_op_decomp_guard_skips"] += 1
492
+ continue
493
+
494
+ # Cache decomposition info for range-based dispatch
495
+ choice.cache_decomposition(decomp, decomp_kwargs)
496
+ # Store config_patches for this choice
497
+ choice.config_patches = config_patches
498
+ choices.append(choice)
499
+
500
+ return choices
501
+
502
+ def _generate_variant_name(
503
+ self, decomp: Callable[..., Any], kwargs: dict[str, Any]
504
+ ) -> str:
505
+ """Generate a descriptive name for a decomposition variant with its parameters."""
506
+ import re
507
+
508
+ base_name = decomp.__name__
509
+ if not kwargs:
510
+ return base_name
511
+
512
+ def sanitize_value(v: Any) -> str:
513
+ """Convert a value to a valid Python identifier component."""
514
+ s = str(v)
515
+ # Replace invalid characters with underscores
516
+ s = re.sub(r"[^a-zA-Z0-9_]", "_", s)
517
+ # Ensure it doesn't start with a digit
518
+ if s and s[0].isdigit():
519
+ s = "_" + s
520
+ return s
521
+
522
+ param_suffix = "_".join(
523
+ f"{k}_{sanitize_value(v)}" for k, v in sorted(kwargs.items())
524
+ )
525
+ return f"{base_name}_{param_suffix}"
526
+
527
+ def _validate_non_tensor_kwargs(self, kwargs: dict[str, Any]) -> None:
528
+ """Validate that kwargs contains only non-tensor arguments."""
529
+ for key, value in kwargs.items():
530
+ if isinstance(value, (torch.Tensor, Buffer)):
531
+ raise AssertionError(
532
+ f"kwargs['{key}'] contains tensor {type(value)}. "
533
+ f"Tensor arguments should be in input_nodes, not kwargs. "
534
+ f"Only scalar/non-tensor parameters should be in kwargs."
535
+ )
536
+
537
+ def _validate_layout_equivalence(
538
+ self,
539
+ op_name: str,
540
+ decompositions: list[Callable[..., Any]],
541
+ layouts: list[Layout],
542
+ ) -> None:
543
+ """Ensure all layouts have consistent stride, device, dtype, and sizes for fair autotuning."""
544
+ if not layouts:
545
+ return
546
+
547
+ reference = layouts[0]
548
+ for i, layout in enumerate(layouts[1:], start=1):
549
+ if (layout.device, layout.dtype, layout.size, layout.stride) != (
550
+ reference.device,
551
+ reference.dtype,
552
+ reference.size,
553
+ reference.stride,
554
+ ):
555
+ raise AssertionError(
556
+ f"Layout mismatch in custom op '{op_name}': "
557
+ f"decomposition '{decompositions[i].__name__}' produces "
558
+ f"({layout.device}, {layout.dtype}, {layout.size}, {layout.stride}) "
559
+ f"but '{decompositions[0].__name__}' produces "
560
+ f"({reference.device}, {reference.dtype}, {reference.size}, {reference.stride})"
561
+ )
562
+
563
+ def _infer_custom_op_layout(
564
+ self,
565
+ input_nodes: list[Buffer],
566
+ function_decomposition: Callable[..., Any],
567
+ kwargs: dict[str, Any],
568
+ default_impl: Callable[..., Any] | None = None,
569
+ input_gen_fns: dict[int, Callable[[Any], torch.Tensor]] | None = None,
570
+ ) -> Layout:
571
+ """Infer output layout for custom ops using the default implementation when available.
572
+ Note that the Subgraph assumes custom ops return exactly one tensor output.
573
+ TODO: Add support for multiple output custom ops.
574
+ """
575
+ import functools
576
+
577
+ from torch._inductor.virtualized import V
578
+
579
+ # Assert kwargs contain only non-tensor arguments
580
+ self._validate_non_tensor_kwargs(kwargs)
581
+
582
+ with V.fake_mode:
583
+ example_inputs = []
584
+ for i, inp in enumerate(input_nodes):
585
+ if input_gen_fns and i in input_gen_fns:
586
+ fake_tensor = input_gen_fns[i](inp)
587
+ else:
588
+ raw_shape = inp.get_size()
589
+ concrete_shape = V.graph.sizevars.optimization_hints(raw_shape)
590
+ raw_stride = inp.get_stride()
591
+ concrete_stride = V.graph.sizevars.optimization_hints(raw_stride)
592
+ fake_tensor = torch.empty_strided(
593
+ concrete_shape,
594
+ concrete_stride,
595
+ dtype=inp.get_dtype(),
596
+ device=inp.get_device(),
597
+ )
598
+ example_inputs.append(fake_tensor)
599
+
600
+ fn = functools.partial(function_decomposition, **kwargs)
601
+ output = fn(*example_inputs)
602
+
603
+ # Assert single output
604
+ if not isinstance(output, torch.Tensor):
605
+ raise AssertionError(
606
+ f"Expected single tensor output, got {type(output)}. "
607
+ f"Multi-output custom ops not yet supported in autotuning."
608
+ )
609
+
610
+ return FixedLayout(
611
+ device=output.device,
612
+ dtype=output.dtype,
613
+ size=output.shape,
614
+ stride=output.stride(),
615
+ )
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_combo_kernel.py ADDED
@@ -0,0 +1,2036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import itertools
3
+ import logging
4
+ import textwrap
5
+ import tokenize
6
+ from collections import defaultdict
7
+ from collections.abc import Callable
8
+ from dataclasses import dataclass
9
+ from functools import cache
10
+ from typing import Any, cast, TYPE_CHECKING
11
+
12
+ import sympy
13
+ from sympy import Integer, Symbol
14
+
15
+ import torch
16
+ from torch.utils._ordered_set import OrderedSet
17
+
18
+
19
+ if TYPE_CHECKING:
20
+ import triton
21
+
22
+ from .. import config, metrics
23
+ from ..runtime.hints import DeviceProperties, TritonMeta
24
+ from ..runtime.runtime_utils import next_power_of_2
25
+ from ..runtime.triton_heuristics import (
26
+ RoundRobinComboKernelGrid,
27
+ SequentialComboKernelGrid,
28
+ SequentialFlattenComboKernelGrid,
29
+ )
30
+ from ..scheduler import BaseSchedulerNode
31
+ from ..stream_utils import (
32
+ coor_benchmark_device_idx,
33
+ coor_device_str,
34
+ get_raw_stream_name,
35
+ )
36
+ from ..utils import (
37
+ clear_on_fresh_cache,
38
+ DeferredLineBase,
39
+ Placeholder,
40
+ triton_version_uses_attrs_dict,
41
+ )
42
+ from ..virtualized import V
43
+ from .common import (
44
+ ArgName,
45
+ ConstexprArg,
46
+ IndentedBuffer,
47
+ InplacedBuffer,
48
+ Kernel,
49
+ PythonPrinter,
50
+ RemovedArg,
51
+ SizeArg,
52
+ TensorArg,
53
+ WorkspaceArg,
54
+ )
55
+ from .simd import NodeInfo, prefix_is_reduction, SIMDScheduling
56
+ from .simd_kernel_features import SIMDKernelFeatures
57
+ from .triton import TritonKernel
58
+ from .triton_utils import (
59
+ config_of,
60
+ equal_1_arg_indices,
61
+ is_unaligned_buffer,
62
+ signature_to_meta,
63
+ )
64
+
65
+
66
+ # Default block sizes used when combo kernel autotuning is disabled.
67
+ DEFAULT_COMBO_BLOCK_SIZE_1D = 1024
68
+ DEFAULT_COMBO_BLOCK_SIZE_2D = 32
69
+
70
+
71
+ log = logging.getLogger(__name__)
72
+ pexpr = PythonPrinter().doprint
73
+ LARGE_NUMELS = 51_200_000
74
+ BLOCK_UTILIZATION = 0.8
75
+
76
+
77
+ def _size_hint(expr: Any) -> int:
78
+ return V.graph.sizevars.optimization_hint(expr, fallback=1)
79
+
80
+
81
+ def _node_partition_log_context(
82
+ node: BaseSchedulerNode, node_info_map: dict[BaseSchedulerNode, NodeInfo]
83
+ ) -> tuple[Any, ...]:
84
+ node_info = node_info_map[node]
85
+ tiling_hints = tuple(
86
+ (str(dim), _size_hint(numel))
87
+ for dim, numel in sorted(
88
+ node_info.tiling.items(), key=lambda item: str(item[0])
89
+ )
90
+ )
91
+ return (
92
+ bool(node_info.features.is_reduction()),
93
+ node_info.is_persistent_reduction,
94
+ tiling_hints,
95
+ _size_hint(node_info.numel),
96
+ _size_hint(node_info.rnumel),
97
+ )
98
+
99
+
100
+ def _partition_separation_log_context(
101
+ separated_nodes: list[BaseSchedulerNode],
102
+ companion_nodes: list[BaseSchedulerNode],
103
+ node_info_map: dict[BaseSchedulerNode, NodeInfo],
104
+ ) -> tuple[tuple[Any, ...], tuple[Any, ...]]:
105
+ return (
106
+ tuple(_node_partition_log_context(n, node_info_map) for n in separated_nodes),
107
+ tuple(_node_partition_log_context(n, node_info_map) for n in companion_nodes),
108
+ )
109
+
110
+
111
+ def _log_partition_separation(
112
+ log_message: str,
113
+ separated_nodes: list[BaseSchedulerNode],
114
+ companion_nodes: list[BaseSchedulerNode],
115
+ node_info_map: dict[BaseSchedulerNode, NodeInfo],
116
+ ) -> None:
117
+ if log.isEnabledFor(logging.DEBUG):
118
+ _log_partition_separation_once(
119
+ log_message,
120
+ len(separated_nodes),
121
+ _partition_separation_log_context(
122
+ separated_nodes, companion_nodes, node_info_map
123
+ ),
124
+ )
125
+
126
+
127
+ # This diagnostic is otherwise repeated once per equivalent recompile.
128
+ @clear_on_fresh_cache
129
+ @cache
130
+ def _log_partition_separation_once(
131
+ log_message: str,
132
+ num_nodes: int,
133
+ partition_context: tuple[tuple[Any, ...], tuple[Any, ...]],
134
+ ) -> None:
135
+ log.debug(
136
+ log_message,
137
+ num_nodes,
138
+ )
139
+
140
+
141
+ def _default_custom_combo_kernel_horizontal_partition(
142
+ nodes: list[BaseSchedulerNode],
143
+ triton_scheduling: SIMDScheduling,
144
+ node_info_map: dict[BaseSchedulerNode, NodeInfo],
145
+ ) -> list[list[BaseSchedulerNode]]:
146
+ """Horizontally partition the given list of nodes into a list of list of nodes where each sublist
147
+ represents a partition. Nodes in different partitions are implemented in different combo kernels.
148
+ Nodes in the same partition are likely to be implemented
149
+ in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args.
150
+
151
+ Input arguments:
152
+ nodes: a list of fused scheduler nodes to partition.
153
+ triton_scheduling: TritonScheduling instance.
154
+ node_info_map: a map from node to NodeInfo NamedTuple
155
+ Output:
156
+ a list of list of nodes with each sublist representing a partition.
157
+
158
+ The default algorithm is to partition nodes based on the following rules:
159
+ 1) nodes with the same number of block dimensions are grouped together.
160
+ 2) large pointwise nodes (numels greater than LARGE_NUMELS) are separated from other nodes.
161
+ 3) large reduce nodes are separated from other nodes.
162
+ """
163
+
164
+ if len(nodes) < 1:
165
+ raise AssertionError(f"expected at least 1 node, got {len(nodes)}")
166
+
167
+ # first partition nodes based on number of block dimensions
168
+ tilings = [node_info_map[n].tiling for n in nodes]
169
+
170
+ max_dims = max(len(t) for t in tilings)
171
+ nodes_per_ndim: list[list[BaseSchedulerNode]] = []
172
+ for i in range(2, max_dims + 1):
173
+ group_per_dim = [n for n, t in zip(nodes, tilings) if len(t) == i]
174
+ reduction = [
175
+ n for n in group_per_dim if node_info_map[n].features.is_reduction()
176
+ ]
177
+ not_reduction = [n for n in group_per_dim if n not in reduction]
178
+ # rnumel > 2048 usually has long execution time
179
+ # BaseSchedulerNode.group[-1][-1] is rnumel for reduction nodes
180
+ # Scheduling heuristic: separate long reductions (rnumel > 2048).
181
+ # Uses optimization_hint with fallback=1 so unbacked defaults to short reduction.
182
+ long_reduction = [
183
+ n
184
+ for n in reduction
185
+ if V.graph.sizevars.optimization_hint(n.group[-1][-1], fallback=1) > 2048 # type: ignore[arg-type]
186
+ ]
187
+ short_reduction = [n for n in reduction if n not in long_reduction]
188
+ very_large_reduction = [
189
+ n
190
+ for n in long_reduction
191
+ if (
192
+ V.graph.sizevars.optimization_hint(node_info_map[n].numel, fallback=1)
193
+ * V.graph.sizevars.optimization_hint(
194
+ node_info_map[n].rnumel, fallback=1
195
+ )
196
+ )
197
+ > LARGE_NUMELS
198
+ ]
199
+ long_reduction = [n for n in long_reduction if n not in very_large_reduction]
200
+ if long_reduction:
201
+ _log_partition_separation(
202
+ "ComboKernels: %d long reduction nodes are separated",
203
+ long_reduction,
204
+ not_reduction + short_reduction,
205
+ node_info_map,
206
+ )
207
+ if very_large_reduction:
208
+ log.debug(
209
+ "ComboKernels: %d very large reduction nodes are separated",
210
+ len(very_large_reduction),
211
+ )
212
+ nodes_per_ndim.extend([node] for node in very_large_reduction)
213
+ large_pointwise = [
214
+ n
215
+ for n in not_reduction
216
+ if not node_info_map[n].features.is_reduction()
217
+ and len(node_info_map[n].tiling) == 2
218
+ and V.graph.sizevars.optimization_hint(
219
+ node_info_map[n].tiling["x"], fallback=1
220
+ )
221
+ > LARGE_NUMELS
222
+ ]
223
+ if large_pointwise:
224
+ companion_nodes = [n for n in not_reduction if n not in large_pointwise]
225
+ # TODO benchmark the performance when large pointwise nodes combining with others
226
+ # Include the non-large pointwise companions because the diagnostic
227
+ # describes a partition decision for the current candidate group.
228
+ _log_partition_separation(
229
+ "ComboKernels: %d large pointwise nodes are separated",
230
+ large_pointwise,
231
+ companion_nodes,
232
+ node_info_map,
233
+ )
234
+ not_reduction = companion_nodes
235
+ nodes_per_ndim.extend([node] for node in large_pointwise)
236
+
237
+ nodes_per_ndim.extend(
238
+ g for g in (not_reduction, short_reduction, long_reduction) if g
239
+ )
240
+
241
+ if sum(len(p) for p in nodes_per_ndim) != len(nodes):
242
+ raise AssertionError("partitioned node count must equal input node count")
243
+ return nodes_per_ndim
244
+
245
+
246
+ _custom_combo_kernel_horizontal_partition_algorithm: Callable[
247
+ [
248
+ list[BaseSchedulerNode],
249
+ SIMDScheduling,
250
+ dict[BaseSchedulerNode, NodeInfo],
251
+ ],
252
+ list[list[BaseSchedulerNode]],
253
+ ] = _default_custom_combo_kernel_horizontal_partition
254
+
255
+
256
+ def set_custom_combo_kernel_horizontal_partition(
257
+ algorithm: Callable[
258
+ [
259
+ list[BaseSchedulerNode],
260
+ SIMDScheduling,
261
+ dict[BaseSchedulerNode, NodeInfo],
262
+ ],
263
+ list[list[BaseSchedulerNode]],
264
+ ],
265
+ ) -> None:
266
+ """Sets the algorithm used to partition nodes into horizontal partitions. Nodes in different partitions
267
+ are implemented in different combo kernels. Nodes in the same partition are likely to be implemented
268
+ in the same combo kernel, but subject to subsequent restrictions like CUDA limits for number of args.
269
+
270
+ The algorithm should take a list of nodes and return a list of list of nodes.
271
+
272
+ The default algorithm is to partition nodes based on number of block dimensions.
273
+ """
274
+ global _custom_combo_kernel_horizontal_partition_algorithm
275
+ _custom_combo_kernel_horizontal_partition_algorithm = algorithm
276
+
277
+
278
+ @dataclass
279
+ class PartitionState:
280
+ partitions: list[list[BaseSchedulerNode]]
281
+ cur_partition: list[BaseSchedulerNode]
282
+ cur_count: int
283
+
284
+ def finalize(self) -> None:
285
+ if self.cur_partition:
286
+ self.partitions.append(self.cur_partition)
287
+
288
+
289
+ @dataclass
290
+ class SubKernelSetup:
291
+ uniquify_block_sizes: list[str]
292
+ lhs_names: list[str]
293
+
294
+
295
+ @dataclass
296
+ class SubKernelCode:
297
+ setup: IndentedBuffer
298
+ body: IndentedBuffer
299
+ setup_lhs_names: list[str]
300
+
301
+
302
+ @dataclass
303
+ class NoinlineSubKernelCall:
304
+ params: list[ArgName]
305
+ call_args: list[str]
306
+ signature_key: tuple[Any, ...]
307
+
308
+
309
+ @dataclass
310
+ class SharedBody:
311
+ body: IndentedBuffer
312
+ placeholder_names: list[str]
313
+ args_by_subkernel: list[list[str]]
314
+ setup_lhs_names: list[str]
315
+
316
+
317
+ @dataclass
318
+ class ComboLaunchConfig:
319
+ kwargs: dict[str, int]
320
+ num_warps: int
321
+ num_stages: int
322
+
323
+
324
+ class ComboKernel(Kernel):
325
+ """
326
+ A kernel that combines multiple sub-kernels into a single fused kernel.
327
+ """
328
+
329
+ @staticmethod
330
+ def _update_partition(
331
+ partition_state: PartitionState,
332
+ node_rw_count: int,
333
+ node_info: BaseSchedulerNode,
334
+ ) -> None:
335
+ if partition_state.cur_count + node_rw_count > config.combo_kernel_max_num_args:
336
+ partition_state.partitions.append(partition_state.cur_partition)
337
+ partition_state.cur_partition = [node_info]
338
+ partition_state.cur_count = node_rw_count
339
+ else:
340
+ partition_state.cur_count += node_rw_count
341
+ partition_state.cur_partition.append(node_info)
342
+
343
+ @staticmethod
344
+ def _base_horizontal_partition(
345
+ subkernel_nodes: list[BaseSchedulerNode],
346
+ triton_scheduling: SIMDScheduling,
347
+ node_info_map: dict[BaseSchedulerNode, NodeInfo],
348
+ custom_algorithm: bool,
349
+ ) -> list[list[BaseSchedulerNode]]:
350
+ """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel)
351
+ for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args
352
+ (read/writes) and to have the same 2D or 1D blocking strategy."""
353
+ # TODO support combination of kernels with different block dimensions
354
+ if len(subkernel_nodes) < 1:
355
+ raise AssertionError(
356
+ f"expected at least 1 subkernel node, got {len(subkernel_nodes)}"
357
+ )
358
+ mixed_sizes = config.combo_kernel_allow_mixed_sizes > 1 or (
359
+ config.combo_kernel_allow_mixed_sizes == 1 and custom_algorithm
360
+ )
361
+
362
+ ndim_to_partition_state: dict[int, PartitionState] = defaultdict(
363
+ lambda: PartitionState([], [], 0)
364
+ )
365
+ yelem_to_partition_state: dict[int, PartitionState] = defaultdict(
366
+ lambda: PartitionState([], [], 0)
367
+ )
368
+ all_partitions = []
369
+
370
+ for node in subkernel_nodes:
371
+ tiled_groups = node_info_map[node].tiling
372
+ node_info = node
373
+
374
+ read_writes = node.read_writes
375
+ read_write_count = len(read_writes.reads) + len(read_writes.writes)
376
+
377
+ ndim = len(tiled_groups)
378
+ if ndim < 2:
379
+ raise AssertionError(f"Combokernel not support tile {tiled_groups}")
380
+
381
+ # Skip 2d reductions (r0_,r1_) and 3D pointwise (x,y,z) from combo
382
+ keys = tiled_groups.keys()
383
+ if ("r0_" in keys and "r1_" in keys) or "z" in keys:
384
+ all_partitions.append([node_info])
385
+ continue
386
+
387
+ if not mixed_sizes and ndim == 3:
388
+ y_elem = tiled_groups["y"]
389
+ partition_state = yelem_to_partition_state[y_elem]
390
+ ComboKernel._update_partition(
391
+ partition_state, read_write_count, node_info
392
+ )
393
+ else:
394
+ if not (mixed_sizes or ndim <= 3):
395
+ raise AssertionError(f"No mixed sizes: tile {tiled_groups}")
396
+ partition_state = ndim_to_partition_state[ndim]
397
+ ComboKernel._update_partition(
398
+ partition_state, read_write_count, node_info
399
+ )
400
+
401
+ for partition_state in ndim_to_partition_state.values():
402
+ partition_state.finalize()
403
+ all_partitions.extend(partition_state.partitions)
404
+ for partition_state in yelem_to_partition_state.values():
405
+ partition_state.finalize()
406
+ all_partitions.extend(partition_state.partitions)
407
+ return all_partitions
408
+
409
+ @staticmethod
410
+ def horizontal_partition(
411
+ nodes: list[BaseSchedulerNode],
412
+ triton_scheduling: SIMDScheduling,
413
+ node_info_map: dict[BaseSchedulerNode, NodeInfo],
414
+ custom_algorithm: bool = False,
415
+ ) -> list[list[BaseSchedulerNode]]:
416
+ """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnum)
417
+ for each subkernel node where each sublist forms a ComboKernel. It horizontally partitions nodes into
418
+ sublists in the following way:
419
+ 1) call _custom_combo_kernel_horizontal_partition_algorithm() if custom_algorithm is True
420
+ 2) then, call _base_horizontal_partition() to partition nodes into sublists, each sublist is
421
+ guaranteed to not exceed CUDA limits for number of args (read/writes) and to have the same
422
+ 2D or 1D blocking strategy.
423
+ """
424
+ if custom_algorithm:
425
+ raw_partitions = _custom_combo_kernel_horizontal_partition_algorithm(
426
+ nodes, triton_scheduling, node_info_map
427
+ )
428
+ else:
429
+ raw_partitions = [nodes]
430
+
431
+ """Generates a list of lists of node info tuples which consist of (fused_nodes, tiling, numel, rnumel)
432
+ for each subkernel node where each sublist is guaranteed to not exceed CUDA limits for number of args
433
+ (read/writes) and to have the same 2D or 1D blocking strategy."""
434
+ all_partitions = []
435
+ for raw_partition in raw_partitions:
436
+ all_partitions.extend(
437
+ ComboKernel._base_horizontal_partition(
438
+ raw_partition, triton_scheduling, node_info_map, custom_algorithm
439
+ )
440
+ )
441
+ return all_partitions
442
+
443
+ class SequentialDispatch:
444
+ """
445
+ The dispatcher which dispatches the subkernels in a sequential manner:
446
+ the blocks are first dispatched to the 1st subkernel (until it is filled),
447
+ then to the 2nd subkernel, and so on.
448
+ The class defines the methods specific to the dispatch algorithm.
449
+ Methods:
450
+ codegen_pid_range(...): codegen the pid range for each subkernel.
451
+ grid(...): codegen the grid size for launching the combo kernel.
452
+ """
453
+
454
+ grid_expr = SequentialComboKernelGrid
455
+
456
+ @classmethod
457
+ def codegen_pid_range(
458
+ cls, kernel: "ComboKernel", num: int, code: IndentedBuffer
459
+ ) -> None:
460
+ if num == 0:
461
+ cls._calculate_xblocks(kernel, code)
462
+ code.splice(f"if pid < num_xblocks_{num}:")
463
+ with code.indent():
464
+ code.splice("pid_offset = pid")
465
+ else:
466
+ code.splice(f"elif pid < num_xblocks_{num}:")
467
+ with code.indent():
468
+ code.splice(f"pid_offset = pid - num_xblocks_{num - 1}")
469
+
470
+ @classmethod
471
+ def _calculate_xblocks(
472
+ cls, kernel: "ComboKernel", code: IndentedBuffer
473
+ ) -> None:
474
+ x_numels_list = kernel.x_numels_list
475
+ for i in range(len(x_numels_list)):
476
+ xnumels, no_x_dim = (
477
+ (x_numels_list[i], False)
478
+ if isinstance(x_numels_list[i], str)
479
+ and cast(str, x_numels_list[i])[0] != "-"
480
+ or (
481
+ isinstance(x_numels_list[i], int)
482
+ and cast(int, x_numels_list[i]) > 0
483
+ )
484
+ else (kernel.min_x_blocks_list[i], True)
485
+ )
486
+ xblock_str = (
487
+ f"tl.cdiv({xnumels}, XBLOCK)" if not no_x_dim else f"{xnumels}"
488
+ )
489
+ if i == 0:
490
+ code.splice(f"num_xblocks_{i} = {xblock_str}")
491
+ else:
492
+ code.splice(f"num_xblocks_{i} = num_xblocks_{i - 1} + {xblock_str}")
493
+
494
+ class SequentialFlattenGridDispatch:
495
+ """
496
+ Flattened grid dispatch for per-subkernel blocks.
497
+ Uses flattened grid (sum of x*y blocks, 1, 1) and computes
498
+ x_pid_offset, y_pid_offset from the flattened pid.
499
+ """
500
+
501
+ grid_expr = SequentialFlattenComboKernelGrid
502
+
503
+ @classmethod
504
+ def codegen_pid_range(
505
+ cls, kernel: "ComboKernel", num: int, code: IndentedBuffer
506
+ ) -> None:
507
+ if num == 0:
508
+ cls._calculate_total_blocks(kernel, code)
509
+ code.splice(f"if pid < num_blocks_{num}:")
510
+ else:
511
+ code.splice(f"elif pid < num_blocks_{num}:")
512
+
513
+ with code.indent():
514
+ # Compute local pid within this subkernel's block range
515
+ if num == 0:
516
+ code.splice("local_pid = pid")
517
+ else:
518
+ code.splice(f"local_pid = pid - num_blocks_{num - 1}")
519
+
520
+ # Compute x/y indices from flattened local_pid
521
+ if kernel.y_tree_list[num]:
522
+ code.splice(f"x_pid_offset = local_pid % x_blocks_{num}")
523
+ code.splice(f"y_pid_offset = local_pid // x_blocks_{num}")
524
+ else:
525
+ code.splice("x_pid_offset = local_pid")
526
+
527
+ @classmethod
528
+ def _calculate_total_blocks(
529
+ cls, kernel: "ComboKernel", code: IndentedBuffer
530
+ ) -> None:
531
+ """
532
+ Calculate total blocks for each subkernel (x_blocks * y_blocks)
533
+ and cumulative block counts for dispatch boundaries.
534
+ """
535
+ for i, sub_kernel in enumerate(kernel.sub_kernels):
536
+ no_x_dim = sub_kernel.no_x_dim
537
+ xnumel = (
538
+ kernel.min_x_blocks_list[i] if no_x_dim else kernel.x_numels_list[i]
539
+ )
540
+ x_blocks_str = (
541
+ f"tl.cdiv({xnumel}, XBLOCK_{i})" if not no_x_dim else f"{xnumel}"
542
+ )
543
+ code.splice(f"x_blocks_{i} = {x_blocks_str}")
544
+
545
+ if kernel.y_tree_list[i]:
546
+ numel = V.graph.sizevars.simplify(kernel.y_tree_list[i].numel)
547
+ ynumel = (
548
+ int(numel)
549
+ if isinstance(numel, (Integer, int))
550
+ else f"ynumel_{i}"
551
+ )
552
+ code.splice(f"y_blocks_{i} = tl.cdiv({ynumel}, YBLOCK_{i})")
553
+
554
+ blocks_expr = (
555
+ f"x_blocks_{i} * y_blocks_{i}"
556
+ if kernel.y_tree_list[i]
557
+ else f"x_blocks_{i}"
558
+ )
559
+ code.splice(
560
+ f"num_blocks_{i} = {blocks_expr}"
561
+ if i == 0
562
+ else f"num_blocks_{i} = num_blocks_{i - 1} + {blocks_expr}"
563
+ )
564
+
565
+ class RoundRobinDispatch:
566
+ """
567
+ The dispatcher which dispatches the subkernels in a round robin manner:
568
+ the blocks are interleavedly dispatched to each subkernel to execute them
569
+ in parallel.
570
+ The class defines the methods specific to the dispatch algorithm.
571
+ Methods:
572
+ codegen_pid_range(...): codegen the pid range for each subkernel.
573
+ grid(...): codegen the grid size for launching the combo kernel.
574
+ """
575
+
576
+ grid_expr = RoundRobinComboKernelGrid
577
+
578
+ @classmethod
579
+ def codegen_pid_range(
580
+ cls, kernel: "ComboKernel", num: int, code: IndentedBuffer
581
+ ) -> None:
582
+ num_kernels = len(kernel.sub_kernels)
583
+ if num == 0:
584
+ cond = "if"
585
+ else:
586
+ cond = "elif"
587
+ code.splice(f"{cond} pid % {num_kernels} == {num}:")
588
+ with code.indent():
589
+ code.splice(f"pid_offset = pid // {num_kernels}")
590
+
591
+ def __init__(
592
+ self,
593
+ triton_kernel_cls: type[TritonKernel],
594
+ enable_autotune: bool = False,
595
+ mixed_sizes: bool = False,
596
+ per_subkernel_blocks: bool = False,
597
+ ) -> None:
598
+ super().__init__()
599
+ self.triton_kernel_cls = triton_kernel_cls
600
+ self.sub_kernels: list[TritonKernel] = []
601
+ self.iter_vars_count = itertools.count()
602
+ self.grids: list[list[int]] = []
603
+ self.min_x_blocks_list: list[int | str] = []
604
+ self.x_numels_list: list[int | str] = []
605
+ self.y_tree_list: list = []
606
+ self.enable_autotune = enable_autotune
607
+ self.mixed_sizes = mixed_sizes
608
+ self.per_subkernel_blocks = per_subkernel_blocks
609
+ self.dispatch_class: (
610
+ type[
611
+ ComboKernel.SequentialDispatch
612
+ | ComboKernel.SequentialFlattenGridDispatch
613
+ | ComboKernel.RoundRobinDispatch
614
+ ]
615
+ | None
616
+ ) = None
617
+ self.block_args: list[str] = []
618
+ # the following are used when autotuning is disabled
619
+ self.block_size_1d = DEFAULT_COMBO_BLOCK_SIZE_1D
620
+ self.block_size_2d = DEFAULT_COMBO_BLOCK_SIZE_2D
621
+ self.num_warps = 8
622
+ self.block_size_reduce = 256
623
+ self.dynamic_shape_args: list[str] = []
624
+ self.no_bench_stitched_config: triton.Config | None = None
625
+ self.combo_compile_time_autotune = False
626
+ # Compile-time autotune: per-subkernel winning block sizes (XBLOCK_0, ...), passed as args.
627
+ self.stitched_block_config: dict[str, int] | None = None
628
+ # Distinct winner launch configs across the subkernels; seeds the combo's kernel-level autotune.
629
+ self.combo_launch_candidates: list[ComboLaunchConfig] = []
630
+ self.noinline_sub_kernel_calls: list[NoinlineSubKernelCall] = []
631
+ self.noinline_arg_name_maps: list[dict[str, str]] = []
632
+
633
+ @property
634
+ def bake_blocks(self) -> bool:
635
+ """Whether autotuning is disabled and default block values are required.
636
+
637
+ Legacy combo kernels bake these values into the kernel body. Per-subkernel
638
+ block combos pass them as constexpr arguments through default_config.
639
+ """
640
+ return not self.enable_autotune
641
+
642
+ def create_sub_kernel(self, triton_kernel: TritonKernel) -> TritonKernel:
643
+ sub_kernel = triton_kernel
644
+ # pyrefly: ignore [bad-assignment]
645
+ metrics.generated_kernel_count -= 1
646
+ if not self.per_subkernel_blocks:
647
+ sub_kernel.args = self.args
648
+ sub_kernel.iter_vars_count = self.iter_vars_count
649
+ sub_kernel.cse.iter_buffer_ids = self.cse.iter_buffer_ids
650
+ self.sub_kernels.append(sub_kernel)
651
+ return sub_kernel
652
+
653
+ @staticmethod
654
+ def create_triton_kernel(
655
+ tiling: dict[str, sympy.Expr],
656
+ features: SIMDKernelFeatures,
657
+ optimize_mask: bool,
658
+ triton_kernel_cls: type[TritonKernel],
659
+ tiling_scores: dict[str, sympy.Expr] | None = None,
660
+ per_subkernel_blocks: bool = False,
661
+ ) -> TritonKernel:
662
+ """
663
+ Only allow optimize_mask=True when 1) sequential dispatch is used,
664
+ 2) numels except x dimension are the same for each sub kernel.
665
+ """
666
+ # Flattened dispatch: all dimensions derived from single pid
667
+ if per_subkernel_blocks:
668
+ pid_cache = {
669
+ "tl.program_id(0)": "x_pid_offset",
670
+ "tl.program_id(1)": "y_pid_offset",
671
+ }
672
+ else:
673
+ pid_cache = {"tl.program_id(0)": "pid_offset"}
674
+
675
+ kwargs: dict[str, Any] = dict(
676
+ pid_cache=pid_cache,
677
+ optimize_mask=optimize_mask,
678
+ is_combo_kernel=True,
679
+ per_subkernel_blocks=per_subkernel_blocks,
680
+ # foreach kernels don't work with cooperative reductions
681
+ override_cooperative_reduction=False,
682
+ tiling_scores=tiling_scores,
683
+ )
684
+ triton_kernel_cls.apply_feature_required_overrides(features, kwargs)
685
+
686
+ return triton_kernel_cls(tiling, features=features, **kwargs)
687
+
688
+ def codegen_static_numels_sub_kernel(
689
+ self, code: IndentedBuffer, sub_kernel: TritonKernel, num: int
690
+ ) -> SubKernelSetup:
691
+ """
692
+ We get a small speedup from hard coding numels if they are static.
693
+
694
+ This code stomps on the passed-in values by writing an constant to the top of the kernel.
695
+
696
+ In a kernel like:
697
+ def KERNEL_NAME(in_ptr0, in_ptr1, out_ptr2, xnumel, rnumel, XBLOCK : tl.constexpr, R0_BLOCK : tl.constexpr):
698
+
699
+ We would add
700
+ xnumel = 4096
701
+ rnumel = 768
702
+
703
+ After the signature, before the kernel code, if we decided to make these static. As its hardcoded, it becomes
704
+ a better signal to triton on how to unroll and do some static indexing. So, it's not so much that downstream
705
+ knows that its a static numel, as that you just plop a constant into the kernel.
706
+ """
707
+ grid = []
708
+ lhs_names: list[str] = []
709
+ uniquify_block_sizes = []
710
+ for tree in sub_kernel.range_trees:
711
+ simplified_tree_numel = V.graph.sizevars.simplify(tree.numel)
712
+ if isinstance(simplified_tree_numel, (Integer, int)):
713
+ lhs_name = f"{tree.prefix}numel"
714
+ code.writeline(f"{lhs_name} = {int(simplified_tree_numel)}")
715
+ lhs_names.append(lhs_name)
716
+ else:
717
+ if f"{tree.prefix}numel_{num}" not in self.dynamic_shape_args:
718
+ raise AssertionError(
719
+ f"{tree.prefix}numel_{num} not in dynamic_shape_args"
720
+ )
721
+ uniquify_block_sizes.append(f"{tree.prefix}numel")
722
+
723
+ if not tree.is_reduction:
724
+ if isinstance(simplified_tree_numel, (Integer, int)):
725
+ grid.append(int(simplified_tree_numel))
726
+ else:
727
+ # pyrefly: ignore [bad-argument-type]
728
+ grid.append(f"{tree.prefix}numel_{num}")
729
+
730
+ if tree.is_reduction and sub_kernel.persistent_reduction:
731
+ val = TritonKernel._get_persistent_RBLOCK(tree.numel)
732
+ suffix = "" if self.per_subkernel_blocks else f"_{num}"
733
+ lhs_names.append(f"{tree.prefix.upper()}BLOCK{suffix}")
734
+ code.writeline(
735
+ f"{tree.prefix.upper()}BLOCK{suffix}: tl.constexpr = {val}"
736
+ )
737
+
738
+ if tree.prefix == "x" and sub_kernel.no_x_dim:
739
+ suffix = "" if self.per_subkernel_blocks else f"_{num}"
740
+ lhs_names.append(f"XBLOCK{suffix}")
741
+ code.writeline(f"XBLOCK{suffix}: tl.constexpr = 1")
742
+ uniquify_block_sizes.append("XBLOCK")
743
+ elif tree.prefix in ("x", "y") and self.per_subkernel_blocks:
744
+ uniquify_block_sizes.append(f"{tree.prefix.upper()}BLOCK")
745
+ elif tree.is_reduction:
746
+ if self.per_subkernel_blocks or sub_kernel.persistent_reduction:
747
+ uniquify_block_sizes.append(f"{tree.prefix.upper()}BLOCK")
748
+ self.grids.append(grid)
749
+ return SubKernelSetup(
750
+ uniquify_block_sizes=uniquify_block_sizes,
751
+ lhs_names=lhs_names,
752
+ )
753
+
754
+ def min_x_blocks_sub_kernel(self, sub_kernel: TritonKernel, num: int) -> None:
755
+ """
756
+ Kernels with no_x_dim being true has no tunable XBLOCK. They have a fixed number of X blocks.
757
+ Grid calculation needs to make sure that they are assigned with enough number of blocks.
758
+ """
759
+ min_x_blocks: int | str = 0
760
+ x_numels: int | str = 0
761
+ for tree in sub_kernel.range_trees:
762
+ simplified_tree_numel = V.graph.sizevars.simplify(tree.numel)
763
+ if tree.prefix == "x":
764
+ if isinstance(simplified_tree_numel, (Integer, int)):
765
+ x_numels = int(simplified_tree_numel)
766
+ else:
767
+ x_numels = f"{tree.prefix}numel_{num}"
768
+ if sub_kernel.no_x_dim:
769
+ min_x_blocks = x_numels
770
+ x_numels = (
771
+ # pyrefly: ignore [unsupported-operation]
772
+ -min_x_blocks
773
+ if isinstance(x_numels, int)
774
+ # pyrefly: ignore [redundant-cast]
775
+ else "-" + cast(str, x_numels)
776
+ )
777
+ else:
778
+ if isinstance(simplified_tree_numel, (Integer, int)):
779
+ x_numels = int(simplified_tree_numel)
780
+ else:
781
+ x_numels = f"{tree.prefix}numel_{num}"
782
+ self.min_x_blocks_list.append(min_x_blocks)
783
+ self.x_numels_list.append(x_numels)
784
+
785
+ def select_heuristics(self, sub_kernel: TritonKernel) -> tuple[str, dict[str, int]]:
786
+ size_hints = {
787
+ prefix: next_power_of_2(V.graph.sizevars.optimization_hint(numel))
788
+ for prefix, numel in sub_kernel.numels.items()
789
+ if not prefix_is_reduction(prefix) or sub_kernel.inside_reduction
790
+ }
791
+ if sub_kernel.persistent_reduction:
792
+ if not sub_kernel.inside_reduction:
793
+ raise AssertionError(
794
+ "persistent_reduction sub_kernel must be inside_reduction"
795
+ )
796
+ heuristics = "persistent_reduction"
797
+ elif sub_kernel.inside_reduction:
798
+ heuristics = "reduction"
799
+ else:
800
+ heuristics = "pointwise"
801
+ return heuristics, size_hints
802
+
803
+ def select_combo_heuristics(
804
+ self, heuristics_list: list[str], size_hints_list: list[dict[str, int]]
805
+ ) -> tuple[str, dict[str, int], TritonKernel]:
806
+ if not self.enable_autotune and self.no_bench_stitched_config is None:
807
+ return "foreach", size_hints_list[0], self.sub_kernels[0]
808
+ if "reduction" in heuristics_list:
809
+ i, _ = max(
810
+ enumerate(size_hints_list),
811
+ key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "reduction" else 0,
812
+ )
813
+ return heuristics_list[i], size_hints_list[i], self.sub_kernels[i]
814
+ elif "pointwise" in heuristics_list:
815
+ i, _ = max(
816
+ enumerate(size_hints_list),
817
+ key=lambda x: x[1]["x"] if heuristics_list[x[0]] == "pointwise" else 0,
818
+ )
819
+ # modify size_hint to avoid oom check fail (may be a false alarm)
820
+ num_pointwise = len([e for e in heuristics_list if e == "pointwise"])
821
+ num_reduction = len([e for e in heuristics_list if e == "reduction"])
822
+ num_persistent_reduction = len(
823
+ [e for e in heuristics_list if e == "persistent_reduction"]
824
+ )
825
+ if num_reduction != 0:
826
+ raise AssertionError(
827
+ "combining pointwise and reduction are not supported yet."
828
+ )
829
+ heuristics = (
830
+ "pointwise_with_reduction"
831
+ if num_persistent_reduction > 0
832
+ else "pointwise"
833
+ )
834
+ if len(heuristics_list) - num_pointwise >= 4:
835
+ size_hints = size_hints_list[i]
836
+ size_hints["x"] = min(128, size_hints["x"])
837
+ return heuristics, size_hints_list[i], self.sub_kernels[i]
838
+ else:
839
+ # find persistent_reduction with maximum rnumel
840
+ i, _ = max(
841
+ enumerate(size_hints_list),
842
+ key=lambda x: max(
843
+ (v for k, v in x[1].items() if prefix_is_reduction(k))
844
+ ),
845
+ )
846
+ return heuristics_list[i], size_hints_list[i], self.sub_kernels[i]
847
+
848
+ def get_mutated_args_sub_kernels(self) -> list[str]:
849
+ mutated_args: OrderedSet[str] = OrderedSet()
850
+ for num, sub_kernel in enumerate(self.sub_kernels):
851
+ arg_name_map = (
852
+ self.noinline_arg_name_maps[num] if self.per_subkernel_blocks else {}
853
+ )
854
+ for mutation in sub_kernel.mutations:
855
+ if mutation in sub_kernel.args.input_buffers:
856
+ name = sub_kernel.args.input_buffers[mutation]
857
+ mutated_args.add(arg_name_map.get(name, name))
858
+ if (
859
+ mutation in sub_kernel.args.inplace_buffers
860
+ and mutation not in V.graph.removed_buffers
861
+ and mutation not in sub_kernel.removed_buffers
862
+ ):
863
+ name = cast(
864
+ InplacedBuffer, sub_kernel.args.inplace_buffers[mutation]
865
+ ).inner_name
866
+ mutated_args.add(arg_name_map.get(name, name))
867
+ if mutation in sub_kernel.args.output_buffers:
868
+ arg = sub_kernel.args.output_buffers[mutation]
869
+ if isinstance(arg, RemovedArg):
870
+ raise AssertionError("mutated output buffer arg was removed")
871
+ mutated_args.add(arg_name_map.get(arg, arg))
872
+ return sorted(mutated_args)
873
+
874
+ def select_dispatch_strategy(self) -> None:
875
+ if self.dispatch_class is not None:
876
+ return
877
+ if self.per_subkernel_blocks:
878
+ self.dispatch_class = ComboKernel.SequentialFlattenGridDispatch
879
+ return
880
+ # mixed_sizes is used for optimize_mask, so it only allows sequential dispatch
881
+ # Not mixed sizes on y dim technically is ok to use round robin as wells.
882
+ if not self.mixed_sizes or any(isinstance(e, str) for e in self.x_numels_list):
883
+ # str in x_numels_list means a dynamic shape
884
+ self.dispatch_class = ComboKernel.SequentialDispatch
885
+ return
886
+ # A negative x_blocks_list element means the kernel is not tunable,
887
+ # i.e., no_x_dim = True
888
+ x_numels_list = [abs(cast(int, e)) for e in self.x_numels_list]
889
+ total = max(x_numels_list) * len(x_numels_list)
890
+ needed = sum(x_numels_list)
891
+ if needed / total > BLOCK_UTILIZATION:
892
+ # Introduced overhead (masked blocks) is less than 20%
893
+ self.dispatch_class = ComboKernel.RoundRobinDispatch
894
+ else:
895
+ self.dispatch_class = ComboKernel.SequentialDispatch
896
+
897
+ def jit_line(
898
+ self,
899
+ heuristics: str,
900
+ size_hints: dict[str, int],
901
+ selected_kernel: TritonKernel,
902
+ signature: list[Any],
903
+ argdefs: list[ArgName],
904
+ size_hints_list: list[dict[str, int]],
905
+ pointwise_with_reduce: bool = False,
906
+ ) -> str:
907
+ """Write the @triton_heuristics.<heuristics> decorator line for the combo kernel."""
908
+
909
+ can_use_32bit = all(k.index_dtype == "tl.int32" for k in self.sub_kernels)
910
+ size_dtype = "tl.int32" if can_use_32bit else "tl.int64"
911
+ for i, sub in enumerate(self.sub_kernels):
912
+ self.min_x_blocks_sub_kernel(sub, i)
913
+ self.select_dispatch_strategy()
914
+ triton_meta: TritonMeta = cast(
915
+ TritonMeta,
916
+ {
917
+ "signature": signature_to_meta(
918
+ signature, size_dtype=size_dtype, argdefs=argdefs
919
+ ),
920
+ "device": DeviceProperties.create(
921
+ V.graph.get_current_device_or_throw()
922
+ ),
923
+ "constants": {},
924
+ # Inherit enable_fp_fusion, launch_pdl, disable_ftz so combo kernels
925
+ # compile with the same Triton options as standalone kernels.
926
+ **TritonKernel.triton_meta_common(),
927
+ },
928
+ )
929
+
930
+ for arg_num in equal_1_arg_indices(signature):
931
+ triton_meta["constants"][signature[arg_num].name] = 1 # type: ignore[index,union-attr]
932
+
933
+ triton_meta["configs"] = [
934
+ config_of(signature, skip_cpp_wrapper_input_tensor_alignment=True)
935
+ ]
936
+
937
+ mutated_args = self.get_mutated_args_sub_kernels()
938
+ dispatch = self.dispatch_class
939
+ if dispatch is None:
940
+ raise AssertionError("dispatch_class must not be None")
941
+
942
+ # Compute the max persistent R0_BLOCK across sub-kernels.
943
+ # This is used by _reduction_configs() to avoid generating configs
944
+ # where XBLOCK * max_persistent_rblock creates pathologically large
945
+ # tiles that cause extreme ROCm compilation times.
946
+ # The max_persistent_rblock mirrors how R0_BLOCK is computed in
947
+ # codegen_static_numels_sub_kernel() for persistent reductions.
948
+ max_persistent_rblock = 0
949
+ if not self.per_subkernel_blocks:
950
+ max_persistent_rblock = max(
951
+ (
952
+ TritonKernel._get_persistent_RBLOCK(tree.numel)
953
+ for sub in self.sub_kernels
954
+ if sub.persistent_reduction
955
+ for tree in sub.range_trees
956
+ if tree.is_reduction
957
+ ),
958
+ default=0,
959
+ )
960
+
961
+ inductor_meta = {
962
+ "grid_type": dispatch.grid_expr.__name__,
963
+ "combo_grid_meta": self.combo_grid_meta(size_hints_list),
964
+ "kernel_name": str(Placeholder.DESCRIPTIVE_NAME),
965
+ "mutated_arg_names": mutated_args,
966
+ # Matches triton.py:codegen_kernel(): inference/backward graphs skip
967
+ # CPU-copy of mutated args during autotune retries; training-forward
968
+ # graphs must keep it to preserve benchmark inputs across retries.
969
+ "optimize_mem": V.graph.is_inference or V.graph.is_backward,
970
+ **self.triton_kernel_cls.inductor_meta_common(),
971
+ }
972
+ if max_persistent_rblock > 0:
973
+ inductor_meta["max_persistent_rblock"] = max_persistent_rblock
974
+
975
+ # Sum per-sub-kernel bandwidth / FLOP estimates for the combo launch.
976
+ sub_metas = [sub.inductor_meta_per_kernel() for sub in self.sub_kernels]
977
+ self._kernel_num_gb = sum(m.get("kernel_num_gb") or 0 for m in sub_metas)
978
+ if config.benchmark_kernel or config.profile_bandwidth:
979
+ inductor_meta["kernel_num_gb"] = self._kernel_num_gb
980
+ if config.benchmark_kernel:
981
+ inductor_meta["kernel_flop"] = sum(
982
+ m.get("kernel_flop") or 0 for m in sub_metas
983
+ )
984
+
985
+ sub_kernel = selected_kernel
986
+ if heuristics == "foreach":
987
+ heuristics_line = f"""
988
+ @triton_heuristics.foreach(
989
+ filename=__file__,
990
+ triton_meta={triton_meta!r},
991
+ inductor_meta={inductor_meta!r},
992
+ )
993
+ @triton.jit
994
+ """
995
+ elif sub_kernel.inside_reduction:
996
+ reduction_hint = sub_kernel.features.get_reduction_hint(
997
+ sub_kernel.tiling_scores
998
+ )
999
+ heuristics_line = f"""
1000
+ @triton_heuristics.{heuristics}(
1001
+ size_hints={size_hints!r},
1002
+ reduction_hint={reduction_hint},
1003
+ filename=__file__,
1004
+ triton_meta={triton_meta!r},
1005
+ inductor_meta={inductor_meta!r}
1006
+ )
1007
+ @triton.jit
1008
+ """
1009
+ else:
1010
+ tile_hint = ""
1011
+ if len(size_hints) == 2:
1012
+ tile_hint = "tile_hint=TileHint.SQUARE,"
1013
+ else:
1014
+ tile_hint = "tile_hint=TileHint.DEFAULT,"
1015
+ heuristics_line = f"""
1016
+ @triton_heuristics.{heuristics}(
1017
+ size_hints={size_hints!r}, {tile_hint}
1018
+ filename=__file__,
1019
+ triton_meta={triton_meta!r},
1020
+ inductor_meta={inductor_meta!r}
1021
+ )
1022
+ @triton.jit
1023
+ """
1024
+
1025
+ self.triton_meta = triton_meta
1026
+ self.inductor_meta = inductor_meta
1027
+
1028
+ return heuristics_line
1029
+
1030
+ def codegen_blocks(self, code: IndentedBuffer) -> None:
1031
+ has_yblock = any(self.y_tree_list)
1032
+ stitched_kwargs = (
1033
+ self.no_bench_stitched_config.kwargs
1034
+ if self.no_bench_stitched_config is not None
1035
+ else None
1036
+ )
1037
+
1038
+ for block in self.block_args:
1039
+ if stitched_kwargs is not None and block in stitched_kwargs:
1040
+ size = stitched_kwargs[block]
1041
+ elif "YBLOCK" in block:
1042
+ size = self.block_size_2d
1043
+ elif "XBLOCK" in block:
1044
+ size = self.block_size_2d if has_yblock else self.block_size_1d
1045
+ elif "R0_BLOCK" in block:
1046
+ size = self.block_size_reduce
1047
+ else:
1048
+ raise AssertionError(f"{block} is not supported without autotuning")
1049
+ code.splice(f"{block}: tl.constexpr = {size}")
1050
+
1051
+ def get_block_args(self) -> list[ConstexprArg]:
1052
+ """
1053
+ Calculate blocks from sub_kernels and range_trees.
1054
+ Update self.block_args, self.y_tree_list
1055
+ Return the block args
1056
+ """
1057
+ block_names = {}
1058
+ for i, sub_kernel in enumerate(self.sub_kernels):
1059
+ y_tree = None
1060
+ for tree in sub_kernel.range_trees:
1061
+ if tree.is_reduction and (
1062
+ not sub_kernel.inside_reduction or sub_kernel.persistent_reduction
1063
+ ):
1064
+ continue
1065
+ if tree.prefix == "x" and sub_kernel.no_x_dim:
1066
+ continue
1067
+ if tree.prefix == "y":
1068
+ y_tree = tree
1069
+ if self.per_subkernel_blocks:
1070
+ block_names[f"{tree.prefix.upper()}BLOCK_{i}"] = tree.prefix
1071
+ else:
1072
+ block_names[f"{tree.prefix.upper()}BLOCK"] = tree.prefix
1073
+ self.y_tree_list.append(y_tree)
1074
+ self.block_args = list(block_names.keys())
1075
+
1076
+ return [ConstexprArg(x) for x in block_names]
1077
+
1078
+ def add_numel_to_args(
1079
+ self, argdefs: list[ArgName], signature: list[Any]
1080
+ ) -> list[ArgName]:
1081
+ for num, sub_kernel in enumerate(self.sub_kernels):
1082
+ for tree in sub_kernel.active_range_trees():
1083
+ if not isinstance(tree.numel, (Integer, int)):
1084
+ # only if it is a dynamic shape
1085
+ sizearg = SizeArg(f"{tree.prefix}numel_{num}", tree.numel)
1086
+ signature.append(sizearg)
1087
+ argdefs.append(ArgName(f"{tree.prefix}numel_{num}"))
1088
+ self.dynamic_shape_args.append(f"{tree.prefix}numel_{num}")
1089
+ return argdefs
1090
+
1091
+ def add_numel_to_call_args(
1092
+ self, name: str, call_args: list[Any], arg_types: list[Any]
1093
+ ) -> None:
1094
+ for num, sub_kernel in enumerate(self.sub_kernels):
1095
+ for tree in sub_kernel.range_trees:
1096
+ numel_name = f"{tree.prefix}numel_{num}"
1097
+ if numel_name not in self.dynamic_shape_args:
1098
+ continue
1099
+ if isinstance(tree.numel, (Integer, Symbol)):
1100
+ expr = tree.numel
1101
+ else:
1102
+ expr = V.graph.wrapper_code.generate_numel_expr(
1103
+ name, tree, suffix=str(num)
1104
+ )
1105
+
1106
+ if not tree.is_reduction or sub_kernel.inside_reduction:
1107
+ call_args.append(expr)
1108
+ arg_types.append(type(expr))
1109
+
1110
+ def kernel_benchmark_extra_args(self) -> list[str]:
1111
+ extra_args = []
1112
+ for num, sub_kernel in enumerate(self.sub_kernels):
1113
+ for tree in sub_kernel.range_trees:
1114
+ numel_name = f"{tree.prefix}numel_{num}"
1115
+ if numel_name not in self.dynamic_shape_args:
1116
+ continue
1117
+
1118
+ if not tree.is_reduction or sub_kernel.inside_reduction:
1119
+ extra_args.append(
1120
+ str(V.graph.sizevars.optimization_hint(tree.numel))
1121
+ )
1122
+ return extra_args
1123
+
1124
+ def _merge_noinline_kernel_args(self) -> None:
1125
+ for sub_kernel in self.sub_kernels:
1126
+ self._merge_noinline_kernel_arg(sub_kernel)
1127
+
1128
+ self.noinline_arg_name_maps = [
1129
+ self._resolve_noinline_kernel_arg_names(sub_kernel)
1130
+ for sub_kernel in self.sub_kernels
1131
+ ]
1132
+
1133
+ def _merge_noinline_kernel_arg(self, sub_kernel: TritonKernel) -> None:
1134
+ # Each noinline body codegens in a local namespace, so different members
1135
+ # can all have local names like in_ptr0/out_ptr0. First replay every
1136
+ # local arg into the combo-main namespace; names are resolved only after
1137
+ # all members have registered their in-place relationships.
1138
+ local_args = sub_kernel.args
1139
+ local_argdefs, _, local_signature, _ = local_args.python_argdefs()
1140
+
1141
+ for argdef, signature in zip(local_argdefs, local_signature, strict=True):
1142
+ if isinstance(signature, TensorArg):
1143
+ buffer = signature.buffer
1144
+ inplaced = local_args.inplace_buffers.get(buffer)
1145
+ if (
1146
+ inplaced is not None
1147
+ and not isinstance(inplaced, RemovedArg)
1148
+ and inplaced.inner_name == argdef.name
1149
+ ):
1150
+ input_name, *output_names = inplaced.other_names
1151
+ for output_name in output_names:
1152
+ if output_name not in self.args.inplace_buffers:
1153
+ self.args.make_inplace(input_name, output_name)
1154
+ elif local_args.output_buffers.get(buffer) == argdef.name:
1155
+ self.args.output(buffer)
1156
+ else:
1157
+ self.args.input(buffer)
1158
+ elif isinstance(signature, SizeArg):
1159
+ expr = signature.expr
1160
+ if isinstance(expr, Symbol):
1161
+ self.args.size(expr)
1162
+ else:
1163
+ self.args.seed_offset(argdef.name, int(expr))
1164
+
1165
+ def _resolve_noinline_kernel_arg_names(
1166
+ self, sub_kernel: TritonKernel
1167
+ ) -> dict[str, str]:
1168
+ local_args = sub_kernel.args
1169
+ local_to_main: dict[str, str] = {}
1170
+ local_argdefs, _, local_signature, _ = local_args.python_argdefs()
1171
+
1172
+ for argdef, signature in zip(local_argdefs, local_signature, strict=True):
1173
+ if isinstance(signature, TensorArg):
1174
+ buffer = signature.buffer
1175
+ if (
1176
+ buffer in local_args.inplace_buffers
1177
+ or local_args.output_buffers.get(buffer) == argdef.name
1178
+ ):
1179
+ main_name = self.args.output(buffer)
1180
+ else:
1181
+ main_name = self.args.input(buffer)
1182
+ elif isinstance(signature, SizeArg):
1183
+ main_name = self.args.sizevars[signature.expr]
1184
+ else:
1185
+ raise AssertionError(
1186
+ f"unsupported combo noinline argument "
1187
+ f"{argdef.name}: {type(signature).__name__}"
1188
+ )
1189
+
1190
+ local_to_main[argdef.name] = main_name
1191
+
1192
+ return local_to_main
1193
+
1194
+ def _noinline_block_args_for_sub_kernel(
1195
+ self, sub_kernel: TritonKernel, num: int
1196
+ ) -> list[tuple[ArgName, str]]:
1197
+ block_args: list[tuple[ArgName, str]] = []
1198
+ for tree in sub_kernel.range_trees:
1199
+ if tree.prefix == "x" and sub_kernel.no_x_dim:
1200
+ continue
1201
+ if tree.prefix in ("x", "y") or (
1202
+ tree.is_reduction
1203
+ and sub_kernel.inside_reduction
1204
+ and not sub_kernel.persistent_reduction
1205
+ ):
1206
+ name = f"{tree.prefix.upper()}BLOCK"
1207
+ block_args.append((ArgName(name, is_constexpr=True), f"{name}_{num}"))
1208
+ return block_args
1209
+
1210
+ def _signature_key_part(self, arg: Any) -> tuple[Any, ...]:
1211
+ if isinstance(arg, TensorArg):
1212
+ return ("tensor", arg.dtype, is_unaligned_buffer(arg))
1213
+ if isinstance(arg, SizeArg):
1214
+ return ("size", type(arg.expr).__name__)
1215
+ if isinstance(arg, ConstexprArg):
1216
+ return ("constexpr", arg.name)
1217
+ return (type(arg).__name__, getattr(arg, "name", None))
1218
+
1219
+ def _prepare_noinline_sub_kernel_calls(self) -> None:
1220
+ calls: list[NoinlineSubKernelCall] = []
1221
+ for num, sub_kernel in enumerate(self.sub_kernels):
1222
+ local_to_main = self.noinline_arg_name_maps[num]
1223
+ local_argdefs, _, local_signature, _ = sub_kernel.args.python_argdefs()
1224
+ params = list(local_argdefs)
1225
+ call_args = [local_to_main[arg.name] for arg in local_argdefs]
1226
+ signature_key: list[Any] = [
1227
+ self._signature_key_part(arg) for arg in local_signature
1228
+ ]
1229
+
1230
+ for tree in sub_kernel.active_range_trees():
1231
+ if isinstance(tree.numel, (Integer, int)):
1232
+ continue
1233
+ if tree.is_reduction and not sub_kernel.inside_reduction:
1234
+ continue
1235
+ params.append(ArgName(f"{tree.prefix}numel"))
1236
+ call_args.append(f"{tree.prefix}numel_{num}")
1237
+ signature_key.append(("range_numel", tree.prefix))
1238
+
1239
+ params.append(ArgName("x_pid_offset"))
1240
+ call_args.append("x_pid_offset")
1241
+ signature_key.append(("dispatch", "x_pid_offset"))
1242
+ if any(tree.prefix == "y" for tree in sub_kernel.range_trees):
1243
+ params.append(ArgName("y_pid_offset"))
1244
+ call_args.append("y_pid_offset")
1245
+ signature_key.append(("dispatch", "y_pid_offset"))
1246
+
1247
+ for param, call_arg in self._noinline_block_args_for_sub_kernel(
1248
+ sub_kernel, num
1249
+ ):
1250
+ params.append(param)
1251
+ call_args.append(call_arg)
1252
+ signature_key.append(("block", param.full_name()))
1253
+
1254
+ calls.append(
1255
+ NoinlineSubKernelCall(
1256
+ params=params,
1257
+ call_args=call_args,
1258
+ signature_key=tuple(signature_key),
1259
+ )
1260
+ )
1261
+
1262
+ self.noinline_sub_kernel_calls = calls
1263
+
1264
+ def _can_share_body(
1265
+ self,
1266
+ heuristics_list: list[str],
1267
+ ) -> bool:
1268
+ if len(self.sub_kernels) < 2:
1269
+ return False
1270
+ if self.enable_autotune or self.per_subkernel_blocks:
1271
+ return False
1272
+ if torch.version.hip is not None:
1273
+ # The shared-body form joins live pointer placeholders after a
1274
+ # many-way dispatch branch. HIP/Triton currently has pathological
1275
+ # compile times for that IR shape on large foreach lists, so keep
1276
+ # ROCm on the existing per-branch body emission path.
1277
+ return False
1278
+ if self.dispatch_class not in (
1279
+ ComboKernel.SequentialDispatch,
1280
+ ComboKernel.RoundRobinDispatch,
1281
+ ):
1282
+ return False
1283
+ if self.dynamic_shape_args or any(self.y_tree_list):
1284
+ return False
1285
+ if any(
1286
+ sub_kernel.no_x_dim
1287
+ or sub_kernel.inside_reduction
1288
+ or sub_kernel.persistent_reduction
1289
+ for sub_kernel in self.sub_kernels
1290
+ ):
1291
+ return False
1292
+ return all(heuristic == "pointwise" for heuristic in heuristics_list)
1293
+
1294
+ @staticmethod
1295
+ def _plain_lines(code: IndentedBuffer) -> list[str] | None:
1296
+ lines: list[str] = []
1297
+ for line in code._lines:
1298
+ if isinstance(line, str):
1299
+ lines.append(line)
1300
+ elif isinstance(line, DeferredLineBase):
1301
+ evaluated = line()
1302
+ if evaluated is not None:
1303
+ lines.append(evaluated)
1304
+ else:
1305
+ return None
1306
+ return lines
1307
+
1308
+ @staticmethod
1309
+ def _replace_names_in_line(line: str, replacements: dict[str, str]) -> str | None:
1310
+ if not replacements:
1311
+ return line
1312
+ try:
1313
+ pieces: list[str] = []
1314
+ cursor = 0
1315
+ for token in tokenize.generate_tokens(io.StringIO(line).readline):
1316
+ if token.type == tokenize.NAME and token.string in replacements:
1317
+ start, end = token.start[1], token.end[1]
1318
+ pieces.append(line[cursor:start])
1319
+ pieces.append(replacements[token.string])
1320
+ cursor = end
1321
+ pieces.append(line[cursor:])
1322
+ return "".join(pieces)
1323
+ except tokenize.TokenError:
1324
+ return None
1325
+
1326
+ @classmethod
1327
+ def _replace_names(
1328
+ cls, lines: list[str], replacements: dict[str, str]
1329
+ ) -> list[str] | None:
1330
+ replaced: list[str] = []
1331
+ for line in lines:
1332
+ new_line = cls._replace_names_in_line(line, replacements)
1333
+ if new_line is None:
1334
+ return None
1335
+ replaced.append(new_line)
1336
+ return replaced
1337
+
1338
+ @staticmethod
1339
+ def _names_in_lines(lines: list[str]) -> OrderedSet[str] | None:
1340
+ names: OrderedSet[str] = OrderedSet()
1341
+ try:
1342
+ for line in lines:
1343
+ for token in tokenize.generate_tokens(io.StringIO(line).readline):
1344
+ if token.type == tokenize.NAME:
1345
+ names.add(token.string)
1346
+ except tokenize.TokenError:
1347
+ return None
1348
+ return names
1349
+
1350
+ @staticmethod
1351
+ def _range_tree_names(sub_kernel: TritonKernel) -> list[str]:
1352
+ names: list[str] = []
1353
+ for tree in sub_kernel.range_trees:
1354
+ names.append(tree.name)
1355
+ names.extend(entry.name for entry in tree.nodes.values())
1356
+ return names
1357
+
1358
+ @classmethod
1359
+ def _range_tree_name_replacements(
1360
+ cls, first: TritonKernel, sub_kernel: TritonKernel
1361
+ ) -> dict[str, str] | None:
1362
+ if len(first.range_trees) != len(sub_kernel.range_trees):
1363
+ return None
1364
+
1365
+ for first_tree, tree in zip(
1366
+ first.range_trees, sub_kernel.range_trees, strict=True
1367
+ ):
1368
+ if (
1369
+ first_tree.prefix != tree.prefix
1370
+ or first_tree.tensor_dim != tree.tensor_dim
1371
+ or first_tree.is_reduction != tree.is_reduction
1372
+ ):
1373
+ return None
1374
+
1375
+ first_names = cls._range_tree_names(first)
1376
+ names = cls._range_tree_names(sub_kernel)
1377
+ if len(first_names) != len(names):
1378
+ return None
1379
+ return {
1380
+ name: first_name
1381
+ for first_name, name in zip(first_names, names, strict=True)
1382
+ if name != first_name
1383
+ }
1384
+
1385
+ @classmethod
1386
+ def _body_name_replacements(
1387
+ cls,
1388
+ first: TritonKernel,
1389
+ sub_kernel: TritonKernel,
1390
+ args: list[str],
1391
+ ) -> dict[str, str] | None:
1392
+ first_cse_names = {
1393
+ canonical: name for name, canonical in first._op_trace_cse_names.items()
1394
+ }
1395
+ replacements: dict[str, str] = {}
1396
+ for name, canonical in sub_kernel._op_trace_cse_names.items():
1397
+ first_name = first_cse_names.get(canonical)
1398
+ if first_name is None:
1399
+ return None
1400
+ if name != first_name:
1401
+ replacements[name] = first_name
1402
+
1403
+ range_replacements = cls._range_tree_name_replacements(first, sub_kernel)
1404
+ if range_replacements is None:
1405
+ return None
1406
+ replacements.update(range_replacements)
1407
+
1408
+ for i, arg in enumerate(args):
1409
+ replacements[arg] = f"foreach_arg{i}"
1410
+ return replacements
1411
+
1412
+ @staticmethod
1413
+ def _compatible_shared_arg_properties(
1414
+ args_by_subkernel: list[list[str]],
1415
+ tensor_args: dict[str, TensorArg],
1416
+ ) -> bool:
1417
+ if not args_by_subkernel:
1418
+ return False
1419
+ num_args = len(args_by_subkernel[0])
1420
+ if num_args == 0:
1421
+ return False
1422
+ if any(len(args) != num_args for args in args_by_subkernel):
1423
+ return False
1424
+ if any(arg not in tensor_args for args in args_by_subkernel for arg in args):
1425
+ return False
1426
+
1427
+ for arg_index in range(num_args):
1428
+ properties = OrderedSet(
1429
+ [
1430
+ (
1431
+ tensor_args[args[arg_index]].dtype,
1432
+ is_unaligned_buffer(tensor_args[args[arg_index]]),
1433
+ )
1434
+ for args in args_by_subkernel
1435
+ ]
1436
+ )
1437
+ if len(properties) != 1:
1438
+ return False
1439
+
1440
+ return True
1441
+
1442
+ @classmethod
1443
+ def _setup_lhs_names(cls, sub_kernel_codes: list[SubKernelCode]) -> list[str]:
1444
+ names: list[str] = []
1445
+ seen: OrderedSet[str] = OrderedSet()
1446
+ for sub_kernel_code in sub_kernel_codes:
1447
+ for name in sub_kernel_code.setup_lhs_names:
1448
+ if name not in seen:
1449
+ seen.add(name)
1450
+ names.append(name)
1451
+ return names
1452
+
1453
+ def _try_get_shared_body(
1454
+ self,
1455
+ sub_kernel_codes: list[SubKernelCode],
1456
+ signature: list[Any],
1457
+ heuristics_list: list[str],
1458
+ ) -> SharedBody | None:
1459
+ if not self._can_share_body(heuristics_list):
1460
+ return None
1461
+
1462
+ tensor_args = {arg.name: arg for arg in signature if isinstance(arg, TensorArg)}
1463
+ if not tensor_args:
1464
+ return None
1465
+ first_sub_kernel = self.sub_kernels[0]
1466
+ first_trace = first_sub_kernel.op_trace
1467
+ if not first_trace:
1468
+ return None
1469
+ if any(
1470
+ sub_kernel.op_trace != first_trace for sub_kernel in self.sub_kernels[1:]
1471
+ ):
1472
+ return None
1473
+
1474
+ transformed_bodies: list[list[str]] = []
1475
+ args_by_subkernel: list[list[str]] = []
1476
+
1477
+ for sub_kernel, sub_kernel_code in zip(
1478
+ self.sub_kernels, sub_kernel_codes, strict=True
1479
+ ):
1480
+ lines = self._plain_lines(sub_kernel_code.body)
1481
+ if lines is None:
1482
+ return None
1483
+ body_names = self._names_in_lines(lines)
1484
+ if body_names is None:
1485
+ return None
1486
+ if any(
1487
+ arg in body_names and arg not in tensor_args
1488
+ for arg in sub_kernel.op_trace_buffer_arg_names
1489
+ ):
1490
+ return None
1491
+ args = [
1492
+ arg
1493
+ for arg in sub_kernel.op_trace_buffer_arg_names
1494
+ if arg in tensor_args and arg in body_names
1495
+ ]
1496
+ # Every live tensor pointer in the emitted body must come from the
1497
+ # structured trace so placeholder substitution cannot miss it.
1498
+ if any(arg in body_names and arg not in args for arg in tensor_args):
1499
+ return None
1500
+ args_by_subkernel.append(args)
1501
+
1502
+ replacements = self._body_name_replacements(
1503
+ first_sub_kernel, sub_kernel, args
1504
+ )
1505
+ if replacements is None:
1506
+ return None
1507
+ transformed = self._replace_names(lines, replacements)
1508
+ if transformed is None:
1509
+ return None
1510
+
1511
+ transformed_bodies.append(transformed)
1512
+
1513
+ if any(body != transformed_bodies[0] for body in transformed_bodies[1:]):
1514
+ return None
1515
+ if not self._compatible_shared_arg_properties(args_by_subkernel, tensor_args):
1516
+ return None
1517
+
1518
+ setup_lhs_names = self._setup_lhs_names(sub_kernel_codes)
1519
+
1520
+ body = IndentedBuffer()
1521
+ body.writelines(transformed_bodies[0])
1522
+ return SharedBody(
1523
+ body=body,
1524
+ placeholder_names=[
1525
+ f"foreach_arg{i}" for i in range(len(args_by_subkernel[0]))
1526
+ ],
1527
+ args_by_subkernel=args_by_subkernel,
1528
+ setup_lhs_names=setup_lhs_names,
1529
+ )
1530
+
1531
+ def _codegen_sub_kernel_bodies(
1532
+ self,
1533
+ ) -> list[SubKernelCode]:
1534
+ sub_kernel_codes: list[SubKernelCode] = []
1535
+ for num, sub_kernel in enumerate(self.sub_kernels):
1536
+ setup = IndentedBuffer()
1537
+ sub_kernel_setup = self.codegen_static_numels_sub_kernel(
1538
+ setup, sub_kernel, num
1539
+ )
1540
+ sub_kernel.codegen_prologue(sub_kernel.body)
1541
+ sub_kernel.codegen_body()
1542
+ sub_kernel._filter_pdl(sub_kernel.body)
1543
+ uniquify = (
1544
+ []
1545
+ if self.per_subkernel_blocks
1546
+ else sub_kernel_setup.uniquify_block_sizes
1547
+ )
1548
+ body = self.uniquify_block_sizes(sub_kernel.body, num, uniquify)
1549
+ sub_kernel_codes.append(
1550
+ SubKernelCode(
1551
+ setup=setup,
1552
+ body=body,
1553
+ setup_lhs_names=sub_kernel_setup.lhs_names,
1554
+ )
1555
+ )
1556
+ return sub_kernel_codes
1557
+
1558
+ def _codegen_branch(
1559
+ self,
1560
+ code: IndentedBuffer,
1561
+ num: int,
1562
+ sub_kernel_code: SubKernelCode,
1563
+ ) -> None:
1564
+ if self.dispatch_class is None:
1565
+ raise AssertionError("dispatch_class must not be None")
1566
+ self.dispatch_class.codegen_pid_range(self, num, code)
1567
+ with code.indent():
1568
+ code.splice(sub_kernel_code.setup)
1569
+ code.splice(sub_kernel_code.body)
1570
+
1571
+ def _codegen_noinline_sub_kernels(
1572
+ self,
1573
+ code: IndentedBuffer,
1574
+ kernel_name: str,
1575
+ sub_kernel_codes: list[SubKernelCode],
1576
+ ) -> list[str]:
1577
+ """Emit each sub-kernel body as a @triton.jit(noinline=True) device
1578
+ function and return the per-branch call lines."""
1579
+ call_lines: list[str] = []
1580
+ defs = IndentedBuffer()
1581
+ emitted: dict[tuple[Any, ...], str] = {}
1582
+ for num, sub_kernel_code in enumerate(sub_kernel_codes):
1583
+ noinline_call = self.noinline_sub_kernel_calls[num]
1584
+ params = noinline_call.params
1585
+ call_args = noinline_call.call_args
1586
+ key = (
1587
+ sub_kernel_code.setup.getvalue(),
1588
+ sub_kernel_code.body.getvalue(),
1589
+ noinline_call.signature_key,
1590
+ )
1591
+
1592
+ sub_name = emitted.get(key)
1593
+ if sub_name is None:
1594
+ sub_name = f"{kernel_name}_body_{len(emitted)}"
1595
+ emitted[key] = sub_name
1596
+ defs.writeline("")
1597
+ defs.writeline("@triton.jit(noinline=True)")
1598
+ defs.writeline(
1599
+ f"def {sub_name}({', '.join(p.full_name() for p in params)}):"
1600
+ )
1601
+ with defs.indent():
1602
+ defs.splice(sub_kernel_code.setup)
1603
+ defs.splice(sub_kernel_code.body)
1604
+ call_lines.append(f"{sub_name}({', '.join(call_args)})")
1605
+ defs.writeline("")
1606
+ code.splice(defs)
1607
+ return call_lines
1608
+
1609
+ def _codegen_shared_branches(
1610
+ self,
1611
+ code: IndentedBuffer,
1612
+ sub_kernel_codes: list[SubKernelCode],
1613
+ shared_body: SharedBody,
1614
+ ) -> None:
1615
+ if self.dispatch_class is None:
1616
+ raise AssertionError("dispatch_class must not be None")
1617
+ for num, sub_kernel_code in enumerate(sub_kernel_codes):
1618
+ self.dispatch_class.codegen_pid_range(self, num, code)
1619
+ with code.indent():
1620
+ code.splice(sub_kernel_code.setup)
1621
+ for placeholder, arg in zip(
1622
+ shared_body.placeholder_names,
1623
+ shared_body.args_by_subkernel[num],
1624
+ strict=True,
1625
+ ):
1626
+ code.writeline(f"{placeholder} = {arg}")
1627
+
1628
+ code.splice("else:")
1629
+ with code.indent():
1630
+ code.splice("pid_offset = 0")
1631
+ for name in shared_body.setup_lhs_names:
1632
+ code.writeline(f"{name} = 0")
1633
+ for placeholder, arg in zip(
1634
+ shared_body.placeholder_names,
1635
+ shared_body.args_by_subkernel[0],
1636
+ strict=True,
1637
+ ):
1638
+ code.writeline(f"{placeholder} = {arg}")
1639
+
1640
+ code.splice(shared_body.body)
1641
+
1642
+ def codegen_kernel(self, name: str | None = None) -> str:
1643
+ """Generate the triton code for a combo kernel that fuses multiple sub-kernels."""
1644
+ # TODO: is it correct to use the first sub kernel's heuristics?
1645
+ heuristics_list, size_hints_list = [], []
1646
+ for subkernel in self.sub_kernels:
1647
+ h, s = self.select_heuristics(subkernel)
1648
+ heuristics_list.append(h)
1649
+ size_hints_list.append(s)
1650
+ heuristics, size_hints, selected_kernel = self.select_combo_heuristics(
1651
+ heuristics_list, size_hints_list
1652
+ )
1653
+ pointwise_with_reduction, heuristics = (
1654
+ (True, "pointwise")
1655
+ if heuristics == "pointwise_with_reduction"
1656
+ else (False, heuristics)
1657
+ )
1658
+ code = IndentedBuffer()
1659
+
1660
+ code.splice(self.triton_kernel_cls.gen_common_triton_imports())
1661
+ if config.benchmark_combo_kernel:
1662
+ code.splice(self.imports_for_benchmark_kernel())
1663
+
1664
+ seen_helpers: OrderedSet[str] = OrderedSet()
1665
+ for sub_kernel in self.sub_kernels:
1666
+ for helper in sub_kernel.helper_functions:
1667
+ if helper not in seen_helpers:
1668
+ code.writeline("")
1669
+ code.splice(helper)
1670
+ seen_helpers.add(helper)
1671
+
1672
+ if self.per_subkernel_blocks:
1673
+ self._merge_noinline_kernel_args()
1674
+
1675
+ argdefs, _, signature, _ = self.args.python_argdefs()
1676
+ argdefs = self.add_numel_to_args(argdefs, signature)
1677
+ if self.per_subkernel_blocks:
1678
+ main_arg_names = OrderedSet(arg.name for arg in argdefs)
1679
+ mapped_arg_names = OrderedSet(
1680
+ name
1681
+ for name_map in self.noinline_arg_name_maps
1682
+ for name in name_map.values()
1683
+ )
1684
+ missing_arg_names = mapped_arg_names - main_arg_names
1685
+ if missing_arg_names:
1686
+ raise AssertionError(
1687
+ "combo noinline call arguments missing from main signature: "
1688
+ f"{sorted(missing_arg_names)}"
1689
+ )
1690
+ block_args = self.get_block_args()
1691
+ if not self.bake_blocks or self.per_subkernel_blocks:
1692
+ argdefs.extend([ArgName(x.name, is_constexpr=True) for x in block_args])
1693
+ if triton_version_uses_attrs_dict():
1694
+ signature.extend(block_args)
1695
+ if self.per_subkernel_blocks:
1696
+ self._prepare_noinline_sub_kernel_calls()
1697
+
1698
+ kernel_name = name or str(Placeholder.KERNEL_NAME)
1699
+
1700
+ sub_kernel_codes = self._codegen_sub_kernel_bodies()
1701
+ # Sub-functions must be emitted before the main kernel's heuristics
1702
+ # decorator line (triton reads the decorated function's source by
1703
+ # inspection). PDL intrinsics move with each body and proton scopes
1704
+ # wrap the main kernel around the calls, so neither needs the inline
1705
+ # form.
1706
+ noinline_calls: list[str] | None = None
1707
+ if self.per_subkernel_blocks:
1708
+ noinline_calls = self._codegen_noinline_sub_kernels(
1709
+ code, kernel_name, sub_kernel_codes
1710
+ )
1711
+
1712
+ code.splice(
1713
+ self.jit_line(
1714
+ heuristics,
1715
+ size_hints,
1716
+ selected_kernel,
1717
+ pointwise_with_reduce=pointwise_with_reduction,
1718
+ signature=signature,
1719
+ argdefs=argdefs,
1720
+ size_hints_list=size_hints_list,
1721
+ )
1722
+ )
1723
+ code.writeline(
1724
+ f"def {kernel_name}({', '.join(x.full_name() for x in argdefs)}):"
1725
+ )
1726
+
1727
+ with code.indent():
1728
+ if config.triton.proton_profiling:
1729
+ code.writeline(f'pl.enter_scope("{kernel_name}")')
1730
+ code.splice("pid = tl.program_id(0)")
1731
+ if self.bake_blocks and not self.per_subkernel_blocks:
1732
+ self.codegen_blocks(code)
1733
+
1734
+ shared_body = self._try_get_shared_body(
1735
+ sub_kernel_codes, signature, heuristics_list
1736
+ )
1737
+ if shared_body is not None:
1738
+ self._codegen_shared_branches(code, sub_kernel_codes, shared_body)
1739
+ elif noinline_calls is not None:
1740
+ if self.dispatch_class is None:
1741
+ raise AssertionError("dispatch_class must not be None")
1742
+ for num, call_line in enumerate(noinline_calls):
1743
+ self.dispatch_class.codegen_pid_range(self, num, code)
1744
+ with code.indent():
1745
+ code.writeline(call_line)
1746
+ code.splice("else:")
1747
+ with code.indent():
1748
+ code.splice("pass")
1749
+ else:
1750
+ for num, sub_kernel_code in enumerate(sub_kernel_codes):
1751
+ self._codegen_branch(code, num, sub_kernel_code)
1752
+
1753
+ code.splice("else:")
1754
+ with code.indent():
1755
+ code.splice("pass")
1756
+ if config.triton.proton_profiling:
1757
+ code.writeline(f'pl.exit_scope("{kernel_name}")')
1758
+
1759
+ if config.benchmark_combo_kernel:
1760
+ code.splice(self.codegen_kernel_benchmark(num_gb=self._kernel_num_gb))
1761
+
1762
+ return code.getvalue()
1763
+
1764
+ def codegen_kernel_benchmark(self, num_gb: float) -> IndentedBuffer:
1765
+ """
1766
+ Generates Python code for benchmarking this combo kernel.
1767
+ - Creates example inputs (random tensors, constants, sizes).
1768
+ - Runs the kernel on the current GPU/stream.
1769
+ - Prints runtime (ms) and throughput (GB/s) using `num_gb`.
1770
+ Args:
1771
+ num_gb (float): The number of gigabytes to use for throughput calculation.
1772
+ Returns:
1773
+ IndentedBuffer: A buffer containing the generated Python benchmark code.
1774
+ """
1775
+ result = IndentedBuffer()
1776
+ _argdefs, call_args, signature, _ = self.args.python_argdefs()
1777
+ result.writelines(["", "", "def get_args():"])
1778
+ with result.indent():
1779
+ name_cnt = itertools.count()
1780
+ var_names = []
1781
+ for arg_name, arg_sig in zip(call_args, signature):
1782
+ var_name = f"arg_{next(name_cnt)}"
1783
+ buf = V.graph.try_get_buffer(arg_name)
1784
+ if buf:
1785
+ size = V.graph.sizevars.optimization_hints(buf.get_size())
1786
+ stride = V.graph.sizevars.optimization_hints(buf.get_stride())
1787
+ result.writeline(
1788
+ f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(buf.get_device())}', dtype={buf.get_dtype()})"
1789
+ )
1790
+ elif arg_name in V.graph.constants:
1791
+ # note that random seed is put in V.graph.constants
1792
+ const_tensor = V.graph.constants[arg_name]
1793
+ size = V.graph.sizevars.optimization_hints(const_tensor.size())
1794
+ stride = V.graph.sizevars.optimization_hints(const_tensor.stride())
1795
+ result.writeline(
1796
+ f"{var_name} = rand_strided({size}, {stride}, device='{coor_device_str(const_tensor.device)}', dtype={const_tensor.dtype})" # type: ignore[arg-type]
1797
+ )
1798
+ elif isinstance(arg_sig, SizeArg):
1799
+ symval_hint = V.graph.sizevars.optimization_hint(arg_sig.expr)
1800
+
1801
+ # Force the seed_offset to be 0 so calls to the same kernel
1802
+ # using different seed offset will have the same benchmark harness.
1803
+ # We can dedup kernel definitions in this case.
1804
+ if "seed_offset" in arg_sig.name:
1805
+ symval_hint = 0
1806
+ result.writeline(f"{var_name} = {symval_hint}")
1807
+ elif isinstance(arg_sig, WorkspaceArg):
1808
+ device = V.graph.get_current_device_or_throw()
1809
+ count = V.graph.sizevars.optimization_hint(arg_sig.count)
1810
+ # for benchmark harness, we ignore arg_sig.zero_mode and always zero it
1811
+ result.writeline(
1812
+ f"{var_name} = torch.zeros({count}, device='{coor_device_str(device)}', dtype={arg_sig.dtype})"
1813
+ )
1814
+ else:
1815
+ raise KeyError(
1816
+ f"Don't find the buffer or const tensor for {arg_name}"
1817
+ )
1818
+ var_names.append(var_name)
1819
+ if self.dynamic_shape_args:
1820
+ var_names.extend(self.kernel_benchmark_extra_args())
1821
+ result.writeline(f"return {', '.join(var_names)},")
1822
+
1823
+ result.writelines(["\n", "\n", "def call(args):"])
1824
+ device = V.graph.get_current_device_or_throw()
1825
+ coor_preamble, index = coor_benchmark_device_idx(device.index)
1826
+ with result.indent():
1827
+ if coor_preamble:
1828
+ result.writeline(coor_preamble)
1829
+ result.writeline(f"with {V.graph.device_ops.device_guard(index)}:")
1830
+ with result.indent():
1831
+ result.writeline(
1832
+ V.graph.device_ops.set_device(index)
1833
+ ) # no-op to ensure context
1834
+ stream_name = get_raw_stream_name(device.index)
1835
+ result.writeline(f"{stream_name} = get_raw_stream({index})")
1836
+ result.writeline(
1837
+ f"{str(Placeholder.KERNEL_NAME)}.run(*args, stream={stream_name})"
1838
+ )
1839
+
1840
+ # benchmark all configs
1841
+ result.writelines(["\n", "\n", "def benchmark_all_configs(args):"])
1842
+ with result.indent():
1843
+ if coor_preamble:
1844
+ result.writeline(coor_preamble)
1845
+ result.writeline(f"with {V.graph.device_ops.device_guard(index)}:")
1846
+ with result.indent():
1847
+ result.writeline(
1848
+ V.graph.device_ops.set_device(index)
1849
+ ) # no-op to ensure context
1850
+ result.writeline(
1851
+ f"return {str(Placeholder.KERNEL_NAME)}.benchmark_all_configs(*args)"
1852
+ )
1853
+
1854
+ result.writelines(["\n", "\n", "if __name__ == '__main__':"])
1855
+ with result.indent():
1856
+ result.writeline(
1857
+ "from torch._inductor.runtime.benchmarking import benchmarker"
1858
+ )
1859
+ result.writeline("")
1860
+
1861
+ result.writeline("args = get_args()")
1862
+ result.writeline(
1863
+ f"ms = benchmarker.benchmark(call, fn_args=(args,), device='{device.type}',rep=40)"
1864
+ )
1865
+ result.writeline(f"num_gb = {num_gb}")
1866
+ result.writeline("gb_per_s = num_gb / (ms / 1e3)")
1867
+ result.writeline(
1868
+ 'print(f"{ms:.3f}ms {num_gb:.3f}GB {gb_per_s:.2f}GB/s")'
1869
+ )
1870
+
1871
+ return result
1872
+
1873
+ def imports_for_benchmark_kernel(self) -> str:
1874
+ # Dedent BEFORE substituting get_raw_stream: a multi-line override would
1875
+ # otherwise collapse dedent's common prefix and misindent the imports.
1876
+ return textwrap.dedent(
1877
+ """
1878
+ from torch._dynamo.testing import rand_strided
1879
+ {}
1880
+ import torch
1881
+ """
1882
+ ).format(V.graph.device_ops.import_get_raw_stream_as("get_raw_stream"))
1883
+
1884
+ def uniquify_block_sizes(
1885
+ self, code: IndentedBuffer, num_kernel: int, uniquify: list[str]
1886
+ ) -> IndentedBuffer:
1887
+ if not uniquify:
1888
+ return code
1889
+ modified = IndentedBuffer(initial_indent=code._indent)
1890
+ for line in code._lines:
1891
+ if isinstance(line, str) and (blocks := [e for e in uniquify if e in line]):
1892
+ modified_line = line
1893
+ for block in blocks:
1894
+ modified_line = modified_line.replace(
1895
+ block, f"{block}_{num_kernel}"
1896
+ )
1897
+ modified.writeline(modified_line)
1898
+ elif isinstance(line, DeferredLineBase) and (
1899
+ blocks := [e for e in uniquify if e in line.line]
1900
+ ):
1901
+ modified_line = line.line
1902
+ for block in blocks:
1903
+ modified_line = modified_line.replace(
1904
+ block, f"{block}_{num_kernel}"
1905
+ )
1906
+ new_line = line._new_line(modified_line)
1907
+ modified.writeline(new_line)
1908
+ else:
1909
+ modified.writeline(line)
1910
+ return modified
1911
+
1912
+ def call_kernel(self, name: str) -> None:
1913
+ _, call_args, _, arg_types = self.args.python_argdefs()
1914
+
1915
+ wrapper = V.graph.wrapper_code
1916
+ if self.dispatch_class is None:
1917
+ raise AssertionError("dispatch_class must not be None")
1918
+ if self.dynamic_shape_args:
1919
+ self.add_numel_to_call_args(name, call_args, arg_types)
1920
+
1921
+ wrapper.generate_kernel_call(
1922
+ name,
1923
+ call_args,
1924
+ triton=True,
1925
+ arg_types=arg_types,
1926
+ triton_meta=self.triton_meta,
1927
+ inductor_meta=self.inductor_meta,
1928
+ )
1929
+
1930
+ def combo_grid_meta(self, size_hints_list: list[dict[str, int]]) -> dict[str, Any]:
1931
+ """
1932
+ Build metadata used by combo-kernel grid/dispatch/autotune helpers.
1933
+ """
1934
+ dynamic_shape = bool(self.dynamic_shape_args)
1935
+ num_kernels = len(self.sub_kernels)
1936
+ min_blocks = (
1937
+ max(self.min_x_blocks_list) * num_kernels if not dynamic_shape else None
1938
+ )
1939
+
1940
+ meta: dict[str, Any] = {
1941
+ "num_kernels": num_kernels,
1942
+ "min_blocks": min_blocks,
1943
+ # Captured at codegen time so runtime sees the same value the
1944
+ # source was generated with, regardless of later config changes.
1945
+ "autotune_grouping": config.combo_kernel_autotune_grouping,
1946
+ "block_arg_names": tuple(self.block_args),
1947
+ }
1948
+
1949
+ if self.bake_blocks or self.combo_compile_time_autotune:
1950
+ default_config: dict[str, int] = {}
1951
+ if self.combo_compile_time_autotune:
1952
+ # Compile-time autotune: per-subkernel winning block sizes are passed as args;
1953
+ # num_warps / num_stages / backend kwargs are autotuned over the distinct winner
1954
+ # launch candidates (flattened to tuples so the meta stays repr-serializable).
1955
+ if not self.combo_launch_candidates:
1956
+ raise AssertionError(
1957
+ "compile-time autotune requires at least one launch candidate"
1958
+ )
1959
+ if self.stitched_block_config is not None:
1960
+ default_config = dict(self.stitched_block_config)
1961
+ meta["stitched_launch_candidates"] = [
1962
+ (c.kwargs, c.num_warps, c.num_stages)
1963
+ for c in self.combo_launch_candidates
1964
+ ]
1965
+ elif self.no_bench_stitched_config is not None:
1966
+ stitched = self.no_bench_stitched_config
1967
+ default_config = {
1968
+ k: int(v) for k, v in stitched.kwargs.items() if "BLOCK" in k
1969
+ }
1970
+ meta["stitched_backend_kwargs"] = {
1971
+ k: v for k, v in stitched.kwargs.items() if "BLOCK" not in k
1972
+ }
1973
+ meta["stitched_num_warps"] = stitched.num_warps
1974
+ meta["stitched_num_stages"] = stitched.num_stages
1975
+ elif self.per_subkernel_blocks:
1976
+ # Per-subkernel block sizes: XBLOCK_0, XBLOCK_1, etc.
1977
+ for num, sub_kernel in enumerate(self.sub_kernels):
1978
+ if sub_kernel.no_x_dim:
1979
+ default_config[f"XBLOCK_{num}"] = 1
1980
+ else:
1981
+ block_size = (
1982
+ self.block_size_2d
1983
+ if any(self.y_tree_list)
1984
+ else self.block_size_1d
1985
+ )
1986
+ default_config[f"XBLOCK_{num}"] = block_size
1987
+
1988
+ if self.y_tree_list[num]:
1989
+ default_config[f"YBLOCK_{num}"] = self.block_size_2d
1990
+ else:
1991
+ if "YBLOCK" in self.block_args:
1992
+ default_config = {
1993
+ "XBLOCK": self.block_size_2d,
1994
+ "YBLOCK": self.block_size_2d,
1995
+ }
1996
+ else:
1997
+ default_config = {"XBLOCK": self.block_size_1d}
1998
+ meta["default_config"] = default_config
1999
+ else:
2000
+ meta["default_config"] = None
2001
+
2002
+ for num, sub_kernel in enumerate(self.sub_kernels):
2003
+ meta[f"no_x_dim_{num}"] = sub_kernel.no_x_dim
2004
+
2005
+ if self.per_subkernel_blocks:
2006
+ meta[f"heuristic_{num}"] = (
2007
+ "persistent_reduction"
2008
+ if sub_kernel.persistent_reduction
2009
+ else "reduction"
2010
+ if sub_kernel.inside_reduction
2011
+ else "pointwise"
2012
+ )
2013
+
2014
+ meta[f"size_hints_{num}"] = size_hints_list[num]
2015
+ meta[f"inductor_meta_{num}"] = sub_kernel.inductor_meta_per_kernel()
2016
+ if meta[f"heuristic_{num}"] == "pointwise":
2017
+ if len(size_hints_list[num]) == 2:
2018
+ meta[f"tile_hint_{num}"] = "TileHint.SQUARE"
2019
+ else:
2020
+ meta[f"tile_hint_{num}"] = "TileHint.DEFAULT"
2021
+ else:
2022
+ meta[f"reduction_hint_{num}"] = (
2023
+ sub_kernel.features.get_reduction_hint(
2024
+ sub_kernel.tiling_scores
2025
+ ).name
2026
+ )
2027
+
2028
+ for tree in sub_kernel.range_trees:
2029
+ if not tree.is_reduction:
2030
+ numel_name = f"{tree.prefix}numel_{num}"
2031
+ if numel_name in self.dynamic_shape_args:
2032
+ meta[numel_name] = None
2033
+ else:
2034
+ meta[numel_name] = int(V.graph.sizevars.simplify(tree.numel))
2035
+
2036
+ return meta
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_split_scan.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+
4
+ import sympy
5
+
6
+ from torch._inductor import config
7
+ from torch._inductor.codegen.simd import IterationRangesRoot, prefix_is_reduction
8
+ from torch._inductor.codegen.triton import (
9
+ triton_compute_type,
10
+ TritonCSEVariable,
11
+ TritonKernel,
12
+ )
13
+ from torch._inductor.runtime.triton_heuristics import SplitScanGrid
14
+ from torch.utils._ordered_set import OrderedSet
15
+ from torch.utils._sympy.functions import CeilDiv
16
+
17
+ from ..utils import sympy_product, upcast_compute_type
18
+
19
+
20
+ class TritonSplitScanKernel(TritonKernel):
21
+ """Generates a triton kernel that supports ops.scan calls while also splitting
22
+ the reduction dimension over multiple triton programs.
23
+
24
+ For this kernel, loop numels will always take the form ``(xdim, rdim)``
25
+ and the grid has the shape ``(CeilDiv(rdim, RBLOCK), xdim)``. Communication
26
+ between blocks occurs within a global memory workspace buffer, which
27
+ must be zero-filled before launching the kernel.
28
+
29
+ Note that generation for ``ops.reduction`` is not supported.
30
+
31
+ For details of the communication strategy, see
32
+ https://research.nvidia.com/publication/2016-03_single-pass-parallel-prefix-scan-decoupled-look-back
33
+
34
+ """
35
+
36
+ def __init__(
37
+ self,
38
+ tiling: dict[str, sympy.Expr],
39
+ pid_cache=None,
40
+ fixed_config=None,
41
+ **kwargs,
42
+ ) -> None:
43
+ if pid_cache is not None:
44
+ raise AssertionError("not supported")
45
+ if fixed_config is not None:
46
+ raise AssertionError("not supported")
47
+ super().__init__(
48
+ tiling,
49
+ **kwargs,
50
+ )
51
+ self.no_x_dim = True
52
+
53
+ def should_use_persistent_reduction(self) -> bool:
54
+ return False
55
+
56
+ def should_use_cooperative_reduction(self) -> bool:
57
+ return False
58
+
59
+ def initialize_range_tree(self, pid_cache):
60
+ prefixes = ["y", "x", "r0_"]
61
+ if len(self.numels) > len(prefixes):
62
+ raise AssertionError("z dimension not supported for split scan")
63
+ active_prefixes = prefixes[len(prefixes) - len(self.numels) :]
64
+
65
+ grid_dims = {"r0_": 0, "x": 1, "y": 2}
66
+ for prefix in active_prefixes:
67
+ numel = self.numels[prefix]
68
+ tensor_dim = 0 if prefix_is_reduction(prefix) else None
69
+ grid_dim = grid_dims[prefix]
70
+ self.range_trees.append(
71
+ IterationRangesRoot(
72
+ f"{prefix}index",
73
+ numel,
74
+ prefix,
75
+ grid_dim,
76
+ self, # type: ignore[arg-type]
77
+ pid_cache=pid_cache,
78
+ is_loop=False,
79
+ tensor_dim=tensor_dim,
80
+ grid_dim=grid_dim,
81
+ has_zdim=False,
82
+ )
83
+ )
84
+
85
+ def reduction(self, dtype, src_dtype, reduction_type, value):
86
+ raise NotImplementedError("NYI TritonSplitDimKernel reductions")
87
+
88
+ def scan(self, dtypes, combine_fn, values):
89
+ """
90
+ Perform an associative scan on 'values'.
91
+ """
92
+ import triton.language as tl
93
+
94
+ (dtype,) = dtypes
95
+ (value,) = values
96
+
97
+ dtype = upcast_compute_type(dtype)
98
+ compute_type = triton_compute_type(dtype)
99
+ compute_type_triton = getattr(tl, compute_type[3:])
100
+
101
+ element_nbits = compute_type_triton.primitive_bitwidth
102
+
103
+ scratch_type = "tl.uint32" if element_nbits <= 16 else "tl.uint64"
104
+ scratch_type_triton = getattr(tl, scratch_type[3:])
105
+ scratch_elems_per_block = 3 if element_nbits == 64 else 1
106
+ scratch_nbytes_per_block = scratch_elems_per_block * (
107
+ scratch_type_triton.primitive_bitwidth // 8
108
+ )
109
+
110
+ cse_compute = functools.partial(self.cse.generate, self.compute)
111
+
112
+ if len(self.numels) != 2:
113
+ raise AssertionError("Unexpected tiling")
114
+ min_rblock = config.triton.min_split_scan_rblock
115
+ reduction_numel = sympy_product(
116
+ numel
117
+ for prefix, numel in self.numels.items()
118
+ if prefix_is_reduction(prefix)
119
+ )
120
+ pointwise_numel = sympy_product(
121
+ numel
122
+ for prefix, numel in self.numels.items()
123
+ if not prefix_is_reduction(prefix)
124
+ )
125
+ max_blocks = pointwise_numel * CeilDiv(reduction_numel, min_rblock)
126
+ nbytes = scratch_nbytes_per_block * max_blocks
127
+ scratch_base: str | TritonCSEVariable
128
+ scratch_base, _, offset = self.args.workspace(nelem=nbytes, zero_fill=True)
129
+ if offset != 0:
130
+ scratch_base = f"({scratch_base} + {self.index_to_str(offset)})"
131
+ runtime_rblocks = f"tl.num_programs({self.range_trees[-1].index})"
132
+ scratch_base = (
133
+ f"{scratch_base}.to(tl.pointer_type({scratch_type})) + xoffset * "
134
+ f"{scratch_elems_per_block} * {runtime_rblocks}"
135
+ )
136
+
137
+ masks = OrderedSet(f"{tree.prefix}mask" for tree in self.range_trees)
138
+ self.filter_masks(masks)
139
+ if self._load_mask:
140
+ raise AssertionError("ops.scan not supported inside ops.masked")
141
+
142
+ value = cse_compute(
143
+ f"{value}.to({compute_type})",
144
+ dtype=dtype,
145
+ shape=value.shape,
146
+ )
147
+ value = cse_compute(
148
+ f"tl.broadcast_to({value}, {self.dense_size_str()})",
149
+ dtype=dtype,
150
+ shape=self.dense_size_list(),
151
+ )
152
+
153
+ combine_helper_fn = self._lift_helper(combine_fn, (value,), (dtype,))
154
+ dim = self.triton_tensor_ndim() - 1
155
+ if dim != 0:
156
+ raise AssertionError(f"expected scan dim == 0, got {dim}")
157
+ scan_shape = value.shape
158
+ if scan_shape is None:
159
+ raise AssertionError("expected value.shape to be set")
160
+ reduced_shape = list(scan_shape)
161
+ del reduced_shape[dim]
162
+
163
+ block_sum = cse_compute(
164
+ f"tl.reduce({value}, {dim}, {combine_helper_fn})",
165
+ dtype=dtype,
166
+ shape=reduced_shape,
167
+ )
168
+ exclusive_prefix = self.cse.newvar(
169
+ dtype=dtype,
170
+ shape=reduced_shape,
171
+ )
172
+ if element_nbits == 64:
173
+ self.compute.splice(
174
+ f"""
175
+ {exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback_64(
176
+ {scratch_base},
177
+ {block_sum},
178
+ {self.iteration_ranges_get_pid(self.range_trees[-1])},
179
+ {combine_helper_fn},
180
+ )
181
+ """,
182
+ strip=True,
183
+ )
184
+
185
+ else:
186
+ if element_nbits > 32:
187
+ raise AssertionError(
188
+ f"expected element_nbits <= 32, got {element_nbits}"
189
+ )
190
+ value_as_uint_dtype = f"tl.uint{element_nbits}"
191
+
192
+ self.compute.splice(
193
+ f"""
194
+ {exclusive_prefix} = triton_helpers.exclusive_scan_decoupled_lookback(
195
+ {scratch_base},
196
+ {block_sum},
197
+ {self.iteration_ranges_get_pid(self.range_trees[-1])},
198
+ {combine_helper_fn},
199
+ DTYPE_VALUE_AS_UINT={value_as_uint_dtype},
200
+ DTYPE_PACK={scratch_type},
201
+ )
202
+ """,
203
+ strip=True,
204
+ )
205
+ # Compute final cumsum
206
+ block_scan = cse_compute(
207
+ f"tl.associative_scan({value}, {dim}, {combine_helper_fn})",
208
+ dtype=dtype,
209
+ shape=scan_shape,
210
+ )
211
+ combined_result = cse_compute(
212
+ f"{combine_helper_fn}({exclusive_prefix}, {block_scan})",
213
+ dtype=dtype,
214
+ shape=scan_shape,
215
+ )
216
+ return (
217
+ cse_compute(
218
+ f"tl.where(roffset == 0, {block_scan}, {combined_result})",
219
+ dtype=dtype,
220
+ shape=scan_shape,
221
+ ),
222
+ )
223
+
224
+ def _get_heuristic(self):
225
+ return "split_scan"
226
+
227
+ def _get_grid_type(self) -> type[SplitScanGrid]:
228
+ return SplitScanGrid
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/triton_utils.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from typing import Any
3
+
4
+ import sympy
5
+
6
+ import torch
7
+ from torch.utils._sympy.symbol import symbol_is_type, SymT
8
+
9
+ from .. import config
10
+ from ..runtime.hints import AttrsDescriptorWrapper, DeviceProperties
11
+ from ..utils import (
12
+ _type_of,
13
+ device_supports_fp64,
14
+ expr_fits_within_32bit,
15
+ triton_version_uses_attrs_dict,
16
+ )
17
+ from ..virtualized import V
18
+ from .common import (
19
+ ArgName,
20
+ ConstexprArg,
21
+ KernelArgType,
22
+ SizeArg,
23
+ TensorArg,
24
+ TMADescriptorArg,
25
+ WorkspaceArg,
26
+ )
27
+
28
+
29
+ def should_unwrap_unspec_arg(name: str):
30
+ if V.graph.is_unspec_arg(name):
31
+ # Unwrap on all devices except CPU
32
+ if V.graph.get_current_device_or_throw().type != "cpu":
33
+ return True
34
+ # Only unwrap on CPU if the input is not used as an output
35
+ if name not in V.graph.mutated_buffers:
36
+ return True
37
+ return False
38
+
39
+
40
+ def use_uint8_triton_storage_for_cuda_float8_e4m3fn(
41
+ dtype: torch.dtype,
42
+ arg_name: str | None = None,
43
+ *,
44
+ device: torch.device | None = None,
45
+ ) -> bool:
46
+ # Triton rejects fp8e4nv pointer types before sm89, but eager CUDA can
47
+ # still dequantize float8_e4m3fn values by treating storage as raw bytes.
48
+ if dtype != torch.float8_e4m3fn or torch.version.hip is not None:
49
+ return False
50
+ if arg_name is not None and not arg_name.startswith("in_ptr"):
51
+ return False
52
+
53
+ if device is None:
54
+ try:
55
+ device = V.graph.get_current_device_or_throw()
56
+ except AttributeError:
57
+ return False
58
+
59
+ if device.type != "cuda":
60
+ return False
61
+
62
+ return DeviceProperties.create(device).cc < 89
63
+
64
+
65
+ def signature_of(arg: KernelArgType, *, size_dtype: str | None) -> str:
66
+ if isinstance(arg, TensorArg):
67
+ typ = _type_of(arg.dtype)
68
+ if should_unwrap_unspec_arg(arg.buffer):
69
+ # had unwrapped 0d tensor as scalar
70
+ new_typ = typ.lstrip("*")
71
+ if new_typ in ["fp16", "bf16"]:
72
+ return "fp32"
73
+ else:
74
+ return new_typ
75
+ elif use_uint8_triton_storage_for_cuda_float8_e4m3fn(arg.dtype, arg.name):
76
+ return "*u8"
77
+ else:
78
+ return typ
79
+ if isinstance(arg, SizeArg):
80
+ if arg.expr is None:
81
+ if triton_version_uses_attrs_dict():
82
+ # In newer versions of Triton, the signature includes "None" args
83
+ # and their type is marked as "constexpr"
84
+ return "constexpr"
85
+ else:
86
+ # In older versions of Triton...
87
+ # From triton/runtime/jit.py
88
+ # `None` is nullptr. Implicitly convert to *i8.
89
+ return "*i8"
90
+ elif _arg_equals_1(arg) and triton_version_uses_attrs_dict():
91
+ # In new versions of Triton, if we have an equal-to-1 arg that's marked as a constant,
92
+ # it should be marked as "constexpr" in the signature.
93
+ return "constexpr"
94
+ elif isinstance(arg.expr, (float, sympy.Float)):
95
+ # Python floats are natively fp64, so use fp64 to preserve precision
96
+ if config._use_fp64_for_unbacked_floats and device_supports_fp64(
97
+ V.graph.current_device
98
+ ):
99
+ return "fp64"
100
+ return "fp32"
101
+ elif isinstance(arg.expr, sympy.Symbol) and symbol_is_type(
102
+ arg.expr, (SymT.UNBACKED_FLOAT)
103
+ ):
104
+ # Unbacked floats from .item() should preserve fp64 precision
105
+ if config._use_fp64_for_unbacked_floats and device_supports_fp64(
106
+ V.graph.current_device
107
+ ):
108
+ return "fp64"
109
+ return "fp32"
110
+ elif isinstance(arg.expr, bool):
111
+ return "i1"
112
+
113
+ # if this is an integer
114
+ if size_dtype == "tl.int32":
115
+ return "i32"
116
+ elif size_dtype == "tl.int64":
117
+ return "i64"
118
+ elif size_dtype is None:
119
+ # no hint: we'll see if we know that this is a 32-bit int, and guard if possible.
120
+ int_max = torch.iinfo(torch.int32).max
121
+ if expr_fits_within_32bit(arg.expr):
122
+ V.graph.sizevars.check_leq(arg.expr, int_max)
123
+ return "i32"
124
+ else:
125
+ return "i64"
126
+ else:
127
+ raise NotImplementedError(f"unhandled size_dtype {size_dtype}")
128
+ if isinstance(arg, WorkspaceArg):
129
+ return _type_of(arg.dtype)
130
+ if isinstance(arg, TMADescriptorArg):
131
+ if arg.api_type == "experimental":
132
+ return "nvTmaDesc"
133
+ else:
134
+ # https://github.com/triton-lang/triton/blob/9695baed9b46cf957e08b157bb4133f4a4b331c5/python/triton/runtime/jit.py#L360-L363
135
+ if arg.api_type != "stable":
136
+ raise AssertionError(
137
+ f"expected api_type == 'stable', got {arg.api_type}"
138
+ )
139
+ if arg.block_shape is None:
140
+ raise AssertionError("expected block_shape to not be None")
141
+ if arg.dtype is None:
142
+ raise AssertionError("expected dtype to not be None")
143
+ inner = _type_of(arg.dtype)[1:] # strip the `*`: *fp32 -> fp32
144
+ return f"tensordesc<{inner}{list(arg.block_shape)}>"
145
+ if isinstance(arg, ConstexprArg):
146
+ return "constexpr"
147
+ raise NotImplementedError(f"unhandled {type(arg)}: {arg}")
148
+
149
+
150
+ def non_constexpr_signature(signature):
151
+ new_signature = []
152
+ for arg in signature:
153
+ if not isinstance(arg, ConstexprArg):
154
+ new_signature.append(arg)
155
+
156
+ return new_signature
157
+
158
+
159
+ def select_tile_hint(size_hints, signature):
160
+ """Pick TileHint.SQUARE vs TileHint.DEFAULT for 2D pointwise; None for 1D.
161
+
162
+ SQUARE applies when the kernel has exactly 2 size hints and 4 non-constexpr
163
+ signature args (input, output, and 2 numel args -> a square 2D tile).
164
+ """
165
+ from torch._inductor.runtime.hints import TileHint
166
+
167
+ if len(size_hints) != 2:
168
+ return None
169
+ if len(non_constexpr_signature(signature)) == 4:
170
+ return TileHint.SQUARE
171
+ return TileHint.DEFAULT
172
+
173
+
174
+ def signature_to_meta(
175
+ signature: list[KernelArgType],
176
+ *,
177
+ size_dtype: str | None,
178
+ argdefs: list[ArgName],
179
+ indices: list[int] | None = None,
180
+ is_template: bool = False,
181
+ ) -> dict[str, str]:
182
+ if indices is None:
183
+ indices = list(range(len(signature)))
184
+
185
+ def _decide_tl_dtype(arg):
186
+ # Even if the ks0 symbol itself is within tl.int32 range, it's
187
+ # risky to use tl.int32 dtype since we may have ks0*ks1 later
188
+ # for kernels like torch.mean when dynamic shape is enabled.
189
+ #
190
+ # Check config.triton.use_block_ptr, since Triton block pointer
191
+ # does not support 64bit indexing:
192
+ # https://gist.github.com/shunting314/6a41c776171720ce4561f202dcde0ad6
193
+ #
194
+ # If the triton metadata is for a template, don't use tl.int64 index.
195
+ # Templates like flex attention/decoding uses block pointers which
196
+ # does not support 64 bit indexing.
197
+ if (
198
+ not config.triton.use_block_ptr
199
+ and not is_template
200
+ and isinstance(arg, SizeArg)
201
+ and arg.name.startswith("ks")
202
+ ):
203
+ return "tl.int64"
204
+ return size_dtype
205
+
206
+ return {
207
+ argdefs[i].name: signature_of(arg, size_dtype=_decide_tl_dtype(arg))
208
+ for i, arg in zip(indices, signature)
209
+ }
210
+
211
+
212
+ def _get_buffer_layout(buf_name: str) -> "torch._inductor.ir.Layout":
213
+ """Get the layout for a buffer, handling both scheduler buffers and graph inputs."""
214
+ if V.graph.scheduler:
215
+ layout = V.graph.scheduler.get_buffer_layout(buf_name)
216
+ else:
217
+ buffer = V.graph.try_get_buffer(buf_name)
218
+ # output arg
219
+ if not buffer:
220
+ if buf_name != V.kernel.output_node.name:
221
+ raise AssertionError(
222
+ f"expected buf_name == output_node.name, got {buf_name}"
223
+ )
224
+ layout = V.kernel.output_node.layout
225
+ else:
226
+ layout = buffer.get_layout()
227
+ return layout
228
+
229
+
230
+ def is_unaligned_buffer_name(buf_name: str) -> bool:
231
+ if buf_name in V.graph.unaligned_buffers:
232
+ return True
233
+
234
+ if buf_name in V.graph.graph_inputs:
235
+ # See Note: [Input Alignment handling in Inductor]
236
+ # For graph inputs that is not recorded in V.graph.unaligned_buffers,
237
+ # we know for sure the tensor is aligned.
238
+ return False
239
+
240
+ if buf_name in V.graph.constants:
241
+ # all constants are assumed to be aligned
242
+ return False
243
+
244
+ layout = _get_buffer_layout(buf_name)
245
+ if isinstance(layout, torch._inductor.ir.NonOwningLayout):
246
+ return not layout.maybe_guard_aligned()
247
+ else:
248
+ return False
249
+
250
+
251
+ def is_unaligned_buffer(arg: TensorArg):
252
+ return is_unaligned_buffer_name(arg.buffer)
253
+
254
+
255
+ def _arg_equals_1(arg: KernelArgType) -> bool:
256
+ return (
257
+ isinstance(arg, SizeArg)
258
+ and isinstance(arg.expr, (int, sympy.Integer))
259
+ and V.graph.sizevars.statically_known_equals(arg.expr, 1) # type: ignore[arg-type]
260
+ )
261
+
262
+
263
+ def equal_1_arg_indices(
264
+ args: list[KernelArgType],
265
+ *,
266
+ indices: list[int] | None = None,
267
+ ) -> tuple[int, ...]:
268
+ if indices is None:
269
+ indices = list(range(len(args)))
270
+
271
+ equal_to_1 = tuple(i for i, arg in zip(indices, args) if _arg_equals_1(arg))
272
+
273
+ return equal_to_1
274
+
275
+
276
+ def _is_tensor_within_2gb(arg: TensorArg) -> bool:
277
+ """Check if a tensor argument's storage is provably within 2GB.
278
+
279
+ Mirrors HIPBackend.is_within_2gb() but uses compile-time symbolic analysis
280
+ instead of runtime tensor inspection. This enables canonicalize_pointers to
281
+ decompose pointer arithmetic into (splat(base), offset) form for buffer ops.
282
+ """
283
+ MAX_BYTES = 2**31 - 1
284
+ try:
285
+ # Graph inputs aren't tracked by the scheduler; get their layout
286
+ # from the graph_inputs dict to avoid KeyError in get_buffer_layout.
287
+ if arg.buffer in V.graph.graph_inputs:
288
+ inp = V.graph.graph_inputs[arg.buffer]
289
+ if hasattr(inp, "get_layout"):
290
+ layout = inp.get_layout()
291
+ else:
292
+ return False
293
+ else:
294
+ layout = _get_buffer_layout(arg.buffer)
295
+ storage_bytes = layout.storage_size() * arg.dtype.itemsize
296
+ return V.graph.sizevars.statically_known_true(storage_bytes <= MAX_BYTES)
297
+ except Exception:
298
+ return False
299
+
300
+
301
+ def config_of(
302
+ args: list[KernelArgType],
303
+ *,
304
+ indices: list[int] | None = None,
305
+ pointer_range_override: tuple[int, ...] | None = None,
306
+ skip_cpp_wrapper_input_tensor_alignment: bool = False,
307
+ ) -> Any:
308
+ if indices is None:
309
+ indices = list(range(len(args)))
310
+
311
+ def is_aligned(x: KernelArgType, alignment: int, include_tensor: bool) -> bool:
312
+ """
313
+ Roughly follow triton code here:
314
+ https://github.com/triton-lang/triton/blob/5282ed890d453e10b9ee30076ef89115dd197761/python/triton/runtime/jit.py#L208-L222
315
+ """
316
+ if isinstance(x, TensorArg):
317
+ if include_tensor:
318
+ offset_aligned = V.graph.sizevars.statically_known_multiple_of(
319
+ x.offset * x.dtype.itemsize,
320
+ alignment, # type: ignore[arg-type]
321
+ )
322
+ return offset_aligned and not is_unaligned_buffer(x)
323
+ else:
324
+ return False
325
+ if isinstance(x, SizeArg):
326
+ # TODO(voz): These are kinda redundant, if we can solve out statically_known_multiple_of with
327
+ # _maybe_evaluate_static...
328
+ if x.name.startswith("load_seed_offset"):
329
+ return False
330
+ if x.expr is None:
331
+ return False
332
+ if isinstance(x.expr, (float, bool)):
333
+ return False
334
+ return V.graph.sizevars.statically_known_multiple_of(x.expr, alignment) # type: ignore[arg-type]
335
+ if isinstance(x, WorkspaceArg):
336
+ # We allocate the workspace ourselves, so it is always aligned
337
+ return True
338
+ if isinstance(x, (TMADescriptorArg, ConstexprArg)):
339
+ return False
340
+ raise NotImplementedError(f"unhandled {type(x)}: {x}")
341
+
342
+ def include_tensor_alignment(arg: KernelArgType) -> bool:
343
+ if (
344
+ not skip_cpp_wrapper_input_tensor_alignment
345
+ or not V.graph.cpp_wrapper
346
+ or V.graph.aot_mode
347
+ or not isinstance(arg, TensorArg)
348
+ or arg.buffer not in V.graph.graph_inputs
349
+ ):
350
+ return True
351
+
352
+ try:
353
+ input_idx = V.graph.graph_input_names.index(arg.buffer)
354
+ except ValueError:
355
+ return True
356
+ return input_idx not in (V.graph.inputs_to_check or ())
357
+
358
+ if config.triton.divisible_by_16:
359
+ divisible_by_16 = tuple(
360
+ i
361
+ for i, arg in zip(indices, args)
362
+ if is_aligned(
363
+ arg,
364
+ alignment=16,
365
+ include_tensor=include_tensor_alignment(arg),
366
+ )
367
+ )
368
+ else:
369
+ divisible_by_16 = ()
370
+
371
+ equal_to_1 = equal_1_arg_indices(args, indices=indices)
372
+
373
+ # On AMD/HIP, tag tensor args whose storage fits in 2GB so Triton
374
+ # can use 32-bit pointer offsets and emit buffer load/store ops.
375
+ if pointer_range_override is not None:
376
+ pointer_range_32 = pointer_range_override
377
+ elif torch.version.hip is not None:
378
+ pointer_range_32 = tuple(
379
+ i
380
+ for i, arg in zip(indices, args)
381
+ if isinstance(arg, TensorArg) and _is_tensor_within_2gb(arg)
382
+ )
383
+ else:
384
+ pointer_range_32 = ()
385
+
386
+ # pyrefly: ignore [bad-argument-count, bad-argument-type]
387
+ return AttrsDescriptorWrapper(divisible_by_16, equal_to_1, pointer_range_32)
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/wrapper_fxir.py ADDED
@@ -0,0 +1,1412 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import functools
3
+ import logging
4
+ import operator
5
+ import textwrap
6
+ from collections import Counter
7
+ from collections.abc import Callable, Iterable, Sequence
8
+ from typing import Any
9
+
10
+ import sympy
11
+
12
+ import torch
13
+ from torch._export.passes._node_metadata_hook import (
14
+ _node_metadata_hook,
15
+ _set_node_metadata_hook,
16
+ )
17
+ from torch._higher_order_ops.triton_kernel_wrap import (
18
+ TraceableTritonKernelWrapper,
19
+ tracing_triton_hopifier_singleton,
20
+ triton_kernel_wrapper_mutation,
21
+ )
22
+ from torch._inductor.codecache import LambdaFuture, PyCodeCache
23
+ from torch._inductor.runtime.triton_heuristics import CachingAutotuner
24
+ from torch._inductor.select_algorithm import extern_kernels # noqa: F401
25
+ from torch._inductor.utils import convert_to_symint
26
+ from torch._inductor.virtualized import V
27
+ from torch._library.triton import wrap_triton
28
+ from torch.fx import GraphModule
29
+ from torch.fx.experimental.symbolic_shapes import (
30
+ CallMethodKey,
31
+ ConvertIntKey,
32
+ DivideByKey,
33
+ )
34
+ from torch.utils import _pytree as pytree
35
+ from torch.utils._ordered_set import OrderedSet
36
+ from torch.utils._sympy.functions import FloorDiv
37
+ from torch.utils._sympy.interp import _run_sympy_handler, sympy_interp
38
+ from torch.utils._sympy.reference import OptimizedPythonReferenceAnalysis
39
+ from torch.utils._sympy.solve import try_solve
40
+
41
+ from .. import config, ir
42
+ from ..runtime.triton_compat import Config
43
+ from ..utils import cache_property_on_self, LineContext, ValueWithLineMap
44
+ from .common import (
45
+ CodegenSymbol,
46
+ FileBackedGraphModule,
47
+ WorkspaceArg,
48
+ WorkspaceZeroMode,
49
+ )
50
+ from .wrapper import (
51
+ AllocateLine,
52
+ BufferLike,
53
+ CommentLine,
54
+ DynamicScalarLine,
55
+ EnterDeviceContextManagerLine,
56
+ EnterSubgraphLine,
57
+ ExitDeviceContextManagerLine,
58
+ ExitSubgraphLine,
59
+ ExternKernelAllocLine,
60
+ ExternKernelOutLine,
61
+ FreeIfNotReusedLine,
62
+ FreeLine,
63
+ IndexPutFallbackLine,
64
+ KernelCallLine,
65
+ KernelDefinitionLine,
66
+ Line,
67
+ MultiOutputLine,
68
+ NullLine,
69
+ PythonWrapperCodegen,
70
+ ReinterpretLine,
71
+ ReuseLine,
72
+ ScatterFallbackLine,
73
+ SubgraphPythonWrapperCodegen,
74
+ SwitchLine,
75
+ SymbolicCallArg,
76
+ SymbolicCallArgLine,
77
+ UnbackedSymbolDefsLine,
78
+ WrapperLine,
79
+ )
80
+
81
+
82
+ aten = torch.ops.aten
83
+ log = logging.getLogger(__name__)
84
+
85
+
86
+ @dataclasses.dataclass
87
+ class SymbolBuffer(CodegenSymbol):
88
+ """
89
+ Represents a symbolic graph input. Expressions more complex than a single
90
+ sympy.Symbol require a name.
91
+ """
92
+
93
+ expr: sympy.Expr
94
+ name: str | None = None
95
+
96
+ def get_name(self) -> str:
97
+ if self.name is not None:
98
+ return self.name
99
+ if not isinstance(self.expr, sympy.Symbol):
100
+ raise AssertionError(f"expression requires a name: {self.expr}")
101
+ return str(self.expr)
102
+
103
+ def get_example(self) -> torch.Tensor | torch.SymInt:
104
+ sym_int = convert_to_symint(self.expr)
105
+ if not isinstance(sym_int, torch.SymInt):
106
+ raise AssertionError(f"expected torch.SymInt, got {type(sym_int)}")
107
+ return sym_int
108
+
109
+
110
+ CodegenBuffer = BufferLike | SymbolBuffer
111
+
112
+
113
+ @dataclasses.dataclass
114
+ class TritonKernel:
115
+ """
116
+ Stores metadata about Triton kernels for use in FX.
117
+ """
118
+
119
+ tuner: CachingAutotuner
120
+ wrapped: TraceableTritonKernelWrapper
121
+
122
+
123
+ def replace_floor_div(expr: sympy.Expr) -> sympy.Expr:
124
+ """
125
+ Replace sympy.floor with FloorDiv.
126
+ """
127
+
128
+ def replace(expr: sympy.Expr) -> sympy.Expr:
129
+ expr = sympy.together(expr)
130
+
131
+ # Division is represented as a Mul with a Rational factor or a Pow with negative
132
+ # exponent. We convert floor(Mul(...)) to FloorDiv(numerator, denominator) by
133
+ # partitioning factors into the numerator and denominator.
134
+ (numerator, denominator) = (sympy.S.One,) * 2
135
+ for arg in sympy.Mul.make_args(expr):
136
+ if isinstance(arg, sympy.Rational):
137
+ numerator *= arg.numerator
138
+ denominator *= arg.denominator
139
+ elif isinstance(arg, sympy.Pow) and arg.exp.is_negative:
140
+ denominator *= arg.base**-arg.exp
141
+ else:
142
+ numerator *= arg
143
+
144
+ return FloorDiv(numerator, denominator)
145
+
146
+ return expr.replace(sympy.floor, replace)
147
+
148
+
149
+ class WrapperFxCodegen(PythonWrapperCodegen):
150
+ """
151
+ Backend to generate wrapper code as an FX IR graph.
152
+ """
153
+
154
+ supports_caching = False
155
+
156
+ def __init__(self, *args: Any, **kwargs: Any):
157
+ super().__init__(*args, **kwargs)
158
+ self.subgms: dict[str, torch.fx.GraphModule] = {}
159
+
160
+ def codegen_inputs(self) -> None:
161
+ """
162
+ This would generate code for symbolic input shapes, strides, etc.
163
+ Since the FX converter handles this, do nothing here.
164
+ """
165
+
166
+ def codegen_switch(self, node: ir.Switch) -> None:
167
+ """
168
+ Switch/cond codegen normally emits a number of different wrapper lines.
169
+ Instead, FX conversion uses a dedicated line for the whole node.
170
+ """
171
+ self.writeline(SwitchLine(self, node))
172
+ for subgraph in node.branches: # pyrefly: ignore [not-iterable]
173
+ self.codegen_subgraph_common(subgraph)
174
+
175
+ def define_subgraph_launcher_fn(
176
+ self, name: str, subgraph_code: ValueWithLineMap | FileBackedGraphModule
177
+ ) -> None:
178
+ """
179
+ Record subgms as they're generated.
180
+ """
181
+ if not isinstance(subgraph_code, FileBackedGraphModule):
182
+ raise AssertionError(
183
+ f"expected FileBackedGraphModule, got {type(subgraph_code)}"
184
+ )
185
+ self.subgms[name] = subgraph_code.gm
186
+
187
+ @property
188
+ @cache_property_on_self
189
+ def is_subgraph(self) -> bool:
190
+ return isinstance(self, SubgraphPythonWrapperCodegen)
191
+
192
+ def get_fx_graph_inputs(
193
+ self,
194
+ ) -> dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr | None]:
195
+ """
196
+ Get the input nodes corresponding to FX graph placeholders.
197
+ """
198
+
199
+ if V.aot_compilation and not self.is_subgraph:
200
+ # AOT graphs must match the signature of the input module.
201
+ return {
202
+ node.name: V.graph.graph_inputs.get(node.name)
203
+ for node in V.graph.module.graph.find_nodes(op="placeholder") # type: ignore[operator, union-attr]
204
+ }
205
+
206
+ return self.get_graph_inputs()
207
+
208
+ def _generate(self, is_inference: bool) -> tuple[FileBackedGraphModule, None]:
209
+ self.run_wrapper_ir_passes(is_inference)
210
+
211
+ prologue = "\n".join(
212
+ [
213
+ self.imports.getvalue(),
214
+ self.header.getvalue(),
215
+ ]
216
+ )
217
+ gm = FxConverter(
218
+ lines=self.lines,
219
+ prologue=prologue,
220
+ graph_inputs=self.get_fx_graph_inputs(),
221
+ graph_outputs=self.get_graph_outputs(),
222
+ subgms=self.subgms,
223
+ is_subgraph=self.is_subgraph,
224
+ ).generate()
225
+
226
+ compiled_fn = self.compile_graph(gm)
227
+
228
+ return FileBackedGraphModule(gm, compiled_fn), None
229
+
230
+ def compile_graph(self, gm: GraphModule) -> Callable[..., Any]:
231
+ """
232
+ Converts the graph module into a runnable function. The default implementation
233
+ is simply an interpreter calling kernels in eager mode. Derived backends can
234
+ override this to do further compilation.
235
+ """
236
+ return gm.forward
237
+
238
+ def write_header(self) -> None:
239
+ """
240
+ Python subgraphs normally lack headers.
241
+ Override this behavior to generate prologues for FX subgraphs.
242
+ """
243
+ PythonWrapperCodegen.write_header(self)
244
+
245
+ def register_alignment_check_inputs(self) -> None:
246
+ """FXIR does not emit deferred alignment copies.
247
+ Alignment is handled by the runtime wrapper."""
248
+
249
+ def codegen_deferred_alignment_copies(
250
+ self, input_names: Iterable[str], stream: int = 0
251
+ ) -> None:
252
+ """FXIR does not emit deferred alignment copies."""
253
+
254
+ @classmethod
255
+ def create(
256
+ cls: type["WrapperFxCodegen"],
257
+ is_subgraph: bool,
258
+ subgraph_name: str | None,
259
+ parent_wrapper: PythonWrapperCodegen | None,
260
+ partition_signatures: ir.GraphPartitionSignature | None = None,
261
+ ) -> "WrapperFxCodegen":
262
+ if is_subgraph:
263
+ if subgraph_name is None:
264
+ raise AssertionError("subgraph_name must not be None for subgraphs")
265
+ if parent_wrapper is None:
266
+ raise AssertionError("parent_wrapper must not be None for subgraphs")
267
+
268
+ # Subgraphs override some methods of PythonWrapperCodegen.
269
+ # Apply these overrides to the user-provided class, with priority given to
270
+ # user-provided methods.
271
+ class SubgraphFxWrapperCodegen(cls, SubgraphPythonWrapperCodegen): # type: ignore[misc,valid-type]
272
+ def compile_graph(self, gm: GraphModule) -> Callable[..., Any]:
273
+ """
274
+ Skip graph compilation for subgraphs.
275
+ """
276
+
277
+ def crash_if_run(*args: Any) -> None:
278
+ raise NotImplementedError("Cannot run a subgraph in isolation!")
279
+
280
+ return crash_if_run
281
+
282
+ return SubgraphFxWrapperCodegen(
283
+ subgraph_name, parent_wrapper, partition_signatures
284
+ )
285
+
286
+ return cls()
287
+
288
+
289
+ @dataclasses.dataclass
290
+ class FxConverter:
291
+ """
292
+ Generates FX IR from Wrapper IR. As each instance is only meant to be used once, the
293
+ input and output code are stored as attributes.
294
+ """
295
+
296
+ lines: list[Line]
297
+ prologue: str
298
+ graph_inputs: dict[str, ir.TensorBox | ir.TorchBindObject | sympy.Expr | None]
299
+ graph_outputs: list[ir.IRNode]
300
+ subgms: dict[str, torch.fx.GraphModule]
301
+ is_subgraph: bool
302
+
303
+ def __post_init__(self) -> None:
304
+ graph = torch.fx.Graph()
305
+ self.gm = GraphModule({}, graph) # Wrapper FX IR.
306
+ self.buffer_to_node: dict[
307
+ str | None, torch.fx.Node
308
+ ] = {} # Symbol table for codegen.
309
+ self.kernels: dict[str, TritonKernel] = {} # Table to store Triton kernels.
310
+ self._unique_symbol_ids: Counter[str] = Counter()
311
+ self.tracer = torch.fx.proxy.GraphAppendingTracer(graph)
312
+ self.expr_to_proxy: dict[sympy.Expr, torch.fx.Proxy] = {}
313
+
314
+ def _import_kernel(self, code: str, kernel_name: str) -> CachingAutotuner:
315
+ """
316
+ Imports a kernel from source, possibly autotuning block parameters.
317
+ """
318
+ module_code = "\n".join([self.prologue, code])
319
+ mod = PyCodeCache.load(module_code)
320
+ kernel = getattr(mod, kernel_name)
321
+
322
+ if isinstance(kernel, LambdaFuture):
323
+ kernel = kernel.result()
324
+
325
+ if not isinstance(kernel, CachingAutotuner):
326
+ raise NotImplementedError(
327
+ textwrap.dedent(f"""
328
+ Unsupported type for kernel {kernel_name}: {type(kernel)}.
329
+ FX conversion only supports Triton kernels.
330
+ """)
331
+ )
332
+
333
+ # Parallel compile workers strip the Python function from the pickled
334
+ # JITFunction. FXIR stores the JITFunction in the Triton HOP side table,
335
+ # so reload it in the parent before runtime execution can need it.
336
+ kernel._ensure_kernel_loaded()
337
+
338
+ return kernel
339
+
340
+ def _create_as_strided(
341
+ self,
342
+ input_node: torch.fx.Node,
343
+ size: tuple[Any, ...],
344
+ stride: tuple[Any, ...],
345
+ offset: int | sympy.Expr,
346
+ ) -> torch.fx.Node:
347
+ if isinstance(offset, sympy.Expr):
348
+ offset = replace_floor_div(offset)
349
+ return self.gm.graph.call_function(
350
+ torch.as_strided,
351
+ args=(
352
+ input_node,
353
+ self._generate_sym_nodes(size),
354
+ self._generate_sym_nodes(stride),
355
+ self._generate_sym_node(offset),
356
+ ),
357
+ )
358
+
359
+ def _record_allocation(self, buffer: CodegenBuffer, node: torch.fx.Node) -> None:
360
+ """
361
+ Updates the symbol table to record that an Inductor buffer maps to the result of
362
+ an FX node.
363
+ """
364
+ if node in self.buffer_to_node:
365
+ raise AssertionError(f"node already recorded in buffer_to_node: {node}")
366
+ self.buffer_to_node[buffer.get_name()] = node
367
+
368
+ def _free(self, buffer: CodegenBuffer | ir.TorchBindObject) -> None:
369
+ """
370
+ Removes the buffer from the symbol table.
371
+ """
372
+ name = buffer.get_name()
373
+ del self.buffer_to_node[name]
374
+
375
+ def _lookup_args(self, args: tuple[Any, ...]) -> tuple[Any, ...]:
376
+ """
377
+ Maps call args back to FX nodes.
378
+ """
379
+ return tuple(
380
+ self.buffer_to_node[arg]
381
+ if isinstance(arg, str)
382
+ else arg.inner_expr
383
+ if isinstance(arg, SymbolicCallArg)
384
+ else arg
385
+ for arg in args
386
+ )
387
+
388
+ def _get_buffer(self, node: ir.IRNode) -> CodegenBuffer:
389
+ """
390
+ Extract buffer data from an IR node.
391
+ """
392
+ if isinstance(node, (ir.Buffer, WorkspaceArg)):
393
+ return node
394
+ elif isinstance(node, (ir.BaseView, ir.MutableBox)):
395
+ return self._get_buffer(node.data)
396
+ elif isinstance(node, sympy.Symbol):
397
+ return SymbolBuffer(node)
398
+ else:
399
+ raise NotImplementedError(f"Unable to extract buffer from node: {node}")
400
+
401
+ def _generate_size_proxy(
402
+ self, node: torch.fx.Node, expr: sympy.Expr
403
+ ) -> torch.fx.Proxy:
404
+ proxy = torch.fx.Proxy(node, tracer=self.tracer)
405
+ self.expr_to_proxy[expr] = proxy
406
+ return proxy
407
+
408
+ def _generate_graph_inputs(self) -> None:
409
+ """
410
+ Converts graph inputs to FX placeholders.
411
+ """
412
+
413
+ for name, ir_node in self.graph_inputs.items():
414
+ if ir_node is None:
415
+ # Create dummy input nodes to match the input signature
416
+ self.gm.graph.placeholder(name)
417
+ continue
418
+
419
+ # Introduce a new symbol for constant inputs.
420
+ is_constant = isinstance(ir_node, (int, float, sympy.Integer, sympy.Float))
421
+
422
+ # Special handling for dynamic shapes which are not simple symbols.
423
+ is_expr = isinstance(ir_node, sympy.Expr) and not isinstance(
424
+ ir_node, (sympy.Symbol, sympy.Integer, sympy.Float)
425
+ )
426
+ if is_expr and ir_node.is_integer is not True:
427
+ raise NotImplementedError(
428
+ f"Unsupported non-integer symbolic graph input: {ir_node}"
429
+ )
430
+
431
+ if is_constant:
432
+ buffer = SymbolBuffer(sympy.Symbol(name, is_integer=True))
433
+ elif is_expr:
434
+ buffer = SymbolBuffer(ir_node, name=name)
435
+ else:
436
+ buffer = self._get_buffer(ir_node)
437
+ placeholder_node = self.gm.graph.placeholder(buffer.get_name())
438
+ placeholder_node.meta["val"] = (
439
+ ir_node if is_constant else buffer.get_example()
440
+ )
441
+ self._record_allocation(buffer, placeholder_node)
442
+
443
+ # Record symbol definitions for dynamic shapes.
444
+ if isinstance(ir_node, sympy.Expr) and not is_constant:
445
+ self._generate_size_proxy(placeholder_node, ir_node)
446
+
447
+ def _generate_graph_input_shapes(self) -> None:
448
+ """
449
+ Generate nodes creating symints that are part of graph input
450
+ shape/strides.
451
+ """
452
+
453
+ def _codegen_symbol(
454
+ sym_or_exp: sympy.Symbol | sympy.Expr,
455
+ base_node: torch.fx.Node,
456
+ target: torch._ops.OpOverload,
457
+ dim: int,
458
+ ) -> None:
459
+ def codegen_proxy() -> torch.fx.Proxy:
460
+ size_node = self.gm.graph.call_function(target, (base_node, dim))
461
+ size_proxy = self._generate_size_proxy(size_node, sym_or_exp)
462
+ return size_proxy
463
+
464
+ if isinstance(sym_or_exp, sympy.Symbol):
465
+ if sym_or_exp in self.expr_to_proxy:
466
+ return
467
+ codegen_proxy()
468
+
469
+ elif isinstance(sym_or_exp, sympy.Integer):
470
+ return
471
+
472
+ elif isinstance(sym_or_exp, sympy.Expr):
473
+ # Check if we need to solve for an undefined symbol.
474
+ undefined_symbols = [
475
+ sym
476
+ for sym in sym_or_exp.free_symbols
477
+ if sym not in self.expr_to_proxy
478
+ ]
479
+ if len(undefined_symbols) == 0:
480
+ self._sympy_interp(sym_or_exp)
481
+ return
482
+ elif len(undefined_symbols) > 1:
483
+ raise NotImplementedError(
484
+ f"Underdetermined input expression: {sym_or_exp}"
485
+ )
486
+
487
+ # Define a new symbol for the input size.
488
+ size_proxy = codegen_proxy()
489
+ size_symbol = sympy.Symbol(
490
+ size_proxy.node.name, integer=True, nonnegative=True
491
+ )
492
+ self.expr_to_proxy[size_symbol] = size_proxy
493
+
494
+ self._define_symbol_by_solving(
495
+ sym_or_exp, size_symbol, undefined_symbols[0]
496
+ )
497
+
498
+ for ir_node in self.graph_inputs.values():
499
+ if isinstance(ir_node, ir.TensorBox):
500
+ buffer = self._get_buffer(ir_node)
501
+ placeholder_node = self.buffer_to_node[buffer.get_name()]
502
+
503
+ for dim, size in enumerate(ir_node.get_size()):
504
+ _codegen_symbol(
505
+ size, placeholder_node, torch.ops.aten.sym_size.int, dim
506
+ )
507
+ for dim, stride in enumerate(ir_node.get_stride()):
508
+ _codegen_symbol(
509
+ stride, placeholder_node, torch.ops.aten.sym_stride.int, dim
510
+ )
511
+
512
+ # A compound input binds its whole expression to one placeholder, so a
513
+ # symbol appearing only inside it has no node of its own. Recover it
514
+ # from that placeholder, after the loop above has defined every symbol
515
+ # the tensor shapes determine.
516
+ for ir_node in self.graph_inputs.values():
517
+ if not isinstance(ir_node, sympy.Expr) or isinstance(ir_node, sympy.Symbol):
518
+ continue
519
+ proxy = self.expr_to_proxy.get(ir_node)
520
+ if proxy is None:
521
+ continue
522
+ undefined = [
523
+ sym for sym in ir_node.free_symbols if sym not in self.expr_to_proxy
524
+ ]
525
+ if len(undefined) == 0:
526
+ continue
527
+ elif len(undefined) > 1:
528
+ # One bound value cannot determine several symbols. This is a
529
+ # branch closing over an expression whose symbols come from
530
+ # tensors it does not take, such as y.shape[0] + z.shape[0].
531
+ raise NotImplementedError(
532
+ f"Compound input {ir_node} leaves these symbols undefined: "
533
+ f"{sorted(undefined, key=str)}"
534
+ )
535
+
536
+ # A tensor-derived FX node does not reserve its symbol's name, so a
537
+ # Dummy is what keeps the anchor from colliding with one.
538
+ anchor = sympy.Dummy(proxy.node.name, integer=True)
539
+ self.expr_to_proxy[anchor] = proxy
540
+ self._define_symbol_by_solving(ir_node, anchor, undefined[0])
541
+
542
+ def _generate_graph_constants(self) -> None:
543
+ for name, value in V.graph.constants.items():
544
+ node = self.gm.graph.get_attr(name)
545
+ node.meta["val"] = value
546
+ setattr(self.gm, name, value)
547
+ self.buffer_to_node[name] = node
548
+
549
+ def _generate_buffer(self, node: ir.IRNode) -> torch.fx.Node | None:
550
+ """
551
+ Generates FX IR for transformations on a buffer, such as ReinterpretView.
552
+ Does nothing if no such transformations are present.
553
+ """
554
+
555
+ if isinstance(node, ir.ShapeAsConstantBuffer):
556
+ # Generate FX nodes to compute the shape expression.
557
+ return self._sympy_interp(node.expr).node
558
+
559
+ def generate_to_buffer(node: ir.IRNode) -> BufferLike | None:
560
+ if isinstance(node, (ir.Buffer, WorkspaceArg)):
561
+ return node
562
+ elif isinstance(node, ir.NoneAsConstantBuffer):
563
+ return None
564
+ elif isinstance(node, ir.MutableBox):
565
+ return generate_to_buffer(node.data)
566
+ elif isinstance(node, ir.ReinterpretView):
567
+ # We need to introduce a new symbol if the output is a ReinterpretView.
568
+ # Use a WorkspaceArg for this.
569
+ buffer = self._get_buffer(node.data)
570
+ if not isinstance(buffer, (ir.Buffer, WorkspaceArg)):
571
+ raise AssertionError(
572
+ f"expected ir.Buffer or WorkspaceArg, got {type(buffer)}"
573
+ )
574
+ unique_name = self.gm.graph._graph_namespace.create_name(
575
+ f"{buffer.get_name()}_view", None
576
+ )
577
+ device = buffer.get_device()
578
+ if not device:
579
+ raise AssertionError(f"buffer has no device: {buffer}")
580
+ reused_as = WorkspaceArg(
581
+ count=buffer.get_size(),
582
+ zero_mode=WorkspaceZeroMode.UNINITIALIZED,
583
+ device=device,
584
+ outer_name=unique_name,
585
+ dtype=buffer.get_dtype(),
586
+ )
587
+
588
+ # Generate FX IR for the view.
589
+ self._generate_reinterpret_helper(buffer, reused_as, node.layout)
590
+
591
+ return reused_as
592
+ else:
593
+ raise NotImplementedError(f"Unrecognized buffer/view node: {node}")
594
+
595
+ buffer = generate_to_buffer(node)
596
+ return self.buffer_to_node[buffer.get_name()] if buffer is not None else None
597
+
598
+ def _generate_outputs(
599
+ self,
600
+ ) -> torch.fx.Node | None | list[torch.fx.Node | None]:
601
+ """
602
+ Generate FX IR for graph outputs.
603
+ """
604
+ output_nodes = [
605
+ self._generate_buffer(node) for idx, node in enumerate(self.graph_outputs)
606
+ ]
607
+
608
+ # Parent graphs with single return elements don't use a tuple.
609
+ output_value = (
610
+ output_nodes[0]
611
+ if len(output_nodes) == 1 and not self.is_subgraph
612
+ else output_nodes
613
+ )
614
+
615
+ return output_value
616
+
617
+ def _generate_subgm_getattrs(self) -> None:
618
+ """
619
+ Generate getattr nodes for subgms.
620
+ """
621
+
622
+ def generate_getattr(name: str, subgm: torch.fx.GraphModule) -> torch.fx.Node:
623
+ self.gm.add_submodule(name, subgm)
624
+ node = self.gm.graph.get_attr(name)
625
+ node.meta["val"] = subgm
626
+ return node
627
+
628
+ self.subgm_getattrs = {
629
+ name: generate_getattr(name, subgm) for name, subgm in self.subgms.items()
630
+ }
631
+
632
+ def _get_subgm_attr(self, subgraph: ir.Subgraph) -> torch.fx.Node:
633
+ """
634
+ Look up the getattr node for a subgraph.
635
+ """
636
+ graph = subgraph.graph
637
+ if graph is None:
638
+ raise AssertionError("subgraph.graph must not be None")
639
+ return self.subgm_getattrs[graph.name]
640
+
641
+ def generate(self) -> torch.fx.GraphModule:
642
+ """
643
+ Main entrypoint for FX codegen.
644
+ """
645
+ self._generate_graph_inputs()
646
+ self._generate_graph_constants()
647
+ self._generate_subgm_getattrs()
648
+
649
+ with _set_node_metadata_hook(
650
+ self.gm,
651
+ functools.partial(_node_metadata_hook, fake_mode=V.fake_mode),
652
+ ):
653
+ self._generate_graph_input_shapes()
654
+
655
+ # Generate FX IR from Wrapper IR lines.
656
+ for line in self.lines:
657
+ if isinstance(line, WrapperLine):
658
+ line.codegen_fx(self)(line)
659
+ elif isinstance(line, LineContext):
660
+ # Ignore line context in FX IR.
661
+ pass
662
+ else:
663
+ raise NotImplementedError(
664
+ textwrap.dedent(
665
+ f"""
666
+ Found line of unrecognized type '{type(line)}':
667
+ '{line}'
668
+
669
+ FX conversion only supports Wrapper IR lines.
670
+ """
671
+ )
672
+ )
673
+
674
+ output = self._generate_outputs()
675
+
676
+ self.gm.graph.output(output)
677
+ self.gm.recompile()
678
+ return self.gm
679
+
680
+ def _sympy_interp(self, expr: sympy.Expr) -> torch.fx.Proxy:
681
+ # hash cons
682
+ if expr in self.expr_to_proxy:
683
+ return self.expr_to_proxy[expr]
684
+ # base cases, don't cache
685
+ if isinstance(
686
+ expr,
687
+ (
688
+ sympy.Integer,
689
+ sympy.Number,
690
+ sympy.Symbol,
691
+ sympy.logic.boolalg.BooleanAtom,
692
+ ),
693
+ ):
694
+ return sympy_interp(
695
+ OptimizedPythonReferenceAnalysis, self.expr_to_proxy, expr
696
+ )
697
+
698
+ # hash cons on arguments, run expr handler
699
+ self.expr_to_proxy[expr] = _run_sympy_handler(
700
+ OptimizedPythonReferenceAnalysis,
701
+ [self._sympy_interp(arg) for arg in expr.args],
702
+ expr,
703
+ )
704
+ return self.expr_to_proxy[expr]
705
+
706
+ def _define_symbol_by_solving(
707
+ self, expr: sympy.Expr, anchor: sympy.Symbol, symbol: sympy.Symbol
708
+ ) -> None:
709
+ """
710
+ Define symbol by solving expr == anchor, which already maps to a proxy.
711
+ """
712
+ # A returned solution directly defines the symbol in terms of the anchor.
713
+ solution = try_solve(sympy.Eq(expr, anchor), symbol)
714
+ if solution is None:
715
+ raise NotImplementedError(
716
+ f"Cannot solve input expression {expr} for {symbol}"
717
+ )
718
+
719
+ symbol_expr = solution[1]
720
+ # If the symbol is an integer, division becomes FloorDiv.
721
+ if symbol.is_integer:
722
+ symbol_expr = replace_floor_div(sympy.floor(symbol_expr))
723
+
724
+ # Generate FX for the symbol.
725
+ self._sympy_interp(symbol_expr)
726
+ self.expr_to_proxy[symbol] = self.expr_to_proxy[symbol_expr]
727
+
728
+ def _generate_sym_node(self, s: int | sympy.Expr) -> int | torch.fx.Node:
729
+ if isinstance(s, (int, sympy.Integer)):
730
+ return int(s)
731
+ elif isinstance(s, sympy.Symbol):
732
+ if s not in self.expr_to_proxy:
733
+ raise AssertionError(
734
+ f"Could not find a node corresponding to the symbol {s}"
735
+ )
736
+ return self.expr_to_proxy[s].node
737
+ elif isinstance(s, sympy.Expr):
738
+ return self._sympy_interp(s).node
739
+
740
+ elif isinstance(s, torch.fx.Node):
741
+ return s
742
+
743
+ else:
744
+ raise ValueError(f"{s} of type {type(s)} is not a valid input")
745
+
746
+ def _generate_sym_nodes(
747
+ self, shape: Sequence[sympy.Expr]
748
+ ) -> list[int | torch.fx.Node]:
749
+ return [self._generate_sym_node(s) for s in shape]
750
+
751
+ def _generate_allocate(self, line: WrapperLine) -> None:
752
+ if not isinstance(line, AllocateLine):
753
+ raise AssertionError(f"expected AllocateLine, got {type(line)}")
754
+ buffer = line.node
755
+ name = buffer.get_name()
756
+ if name in V.graph.removed_buffers:
757
+ raise AssertionError(f"buffer {name} is in removed_buffers")
758
+
759
+ device = buffer.get_device()
760
+ if not device:
761
+ raise AssertionError(f"buffer has no device: {buffer}")
762
+ dtype = buffer.get_dtype()
763
+ shape = self._generate_sym_nodes(buffer.get_size())
764
+ stride = self._generate_sym_nodes(buffer.get_stride())
765
+
766
+ node = self.gm.graph.call_function(
767
+ torch.empty_strided,
768
+ args=(shape, stride),
769
+ kwargs={"dtype": dtype, "device": device.type},
770
+ )
771
+ if not name:
772
+ raise AssertionError(f"buffer has an empty name: {buffer}")
773
+ node.name = name
774
+ self._record_allocation(buffer, node)
775
+
776
+ def _generate_switch(self, line: WrapperLine) -> None:
777
+ if not isinstance(line, SwitchLine):
778
+ raise AssertionError(f"expected SwitchLine, got {type(line)}")
779
+
780
+ ir_node = line.node
781
+ if ir_node.branches is None:
782
+ raise AssertionError("ir_node.branches must not be None")
783
+ if ir_node.operands is None:
784
+ raise AssertionError("ir_node.operands must not be None")
785
+
786
+ def generate_buffer(node: ir.IRNode | None) -> torch.fx.Node | None:
787
+ if node is None:
788
+ raise AssertionError("node must not be None")
789
+ return self._generate_buffer(node)
790
+
791
+ selector = generate_buffer(ir_node.selector)
792
+ operands = tuple(generate_buffer(arg) for arg in ir_node.operands)
793
+ branch_subgms = [self._get_subgm_attr(branch) for branch in ir_node.branches]
794
+
795
+ if ir_node.is_cond:
796
+ # cond expects (selector, true_fn, false_fn, operands) -- branches unpacked positionally.
797
+ if len(branch_subgms) != 2:
798
+ raise AssertionError(
799
+ f"cond requires exactly 2 branches, got {len(branch_subgms)}"
800
+ )
801
+ # branches are stored as [false_fn, true_fn] in ir.Switch
802
+ false_subgm, true_subgm = branch_subgms
803
+ fx_node = self.gm.graph.call_function(
804
+ torch.ops.higher_order.cond,
805
+ args=(selector, true_subgm, false_subgm, operands),
806
+ )
807
+ else:
808
+ # switch expects (selector, [branch_fn, ...], operands) -- branches passed as a list.
809
+ fx_node = self.gm.graph.call_function(
810
+ torch.ops.higher_order.switch,
811
+ args=(selector, branch_subgms, operands),
812
+ )
813
+ self._record_allocation(ir_node, fx_node)
814
+
815
+ def _generate_assert_size_stride(self, line: WrapperLine) -> None:
816
+ pass
817
+
818
+ def _generate_comment(self, line: WrapperLine) -> None:
819
+ if not isinstance(line, CommentLine):
820
+ raise AssertionError(f"expected CommentLine, got {type(line)}")
821
+ # We ignore comments in FX IR.
822
+
823
+ def _generate_dynamic_scalar(self, line: WrapperLine) -> None:
824
+ if not isinstance(line, DynamicScalarLine):
825
+ raise AssertionError(f"expected DynamicScalarLine, got {type(line)}")
826
+
827
+ ir_node = line.node
828
+ (input_ir_node,) = ir_node.inputs
829
+ if not isinstance(input_ir_node, ir.IRNode):
830
+ raise AssertionError(f"expected ir.IRNode, got {type(input_ir_node)}")
831
+ input_fx_node = self._generate_buffer(input_ir_node)
832
+ keypath = ir_node.keypath
833
+ graph = self.gm.graph
834
+
835
+ def generate_item(x: torch.fx.Node | None) -> torch.fx.Node:
836
+ if x is None:
837
+ raise AssertionError("x must not be None")
838
+ return graph.call_function(
839
+ aten.item.default,
840
+ args=(x,),
841
+ )
842
+
843
+ if len(keypath) == 0:
844
+ result_fx_node = generate_item(input_fx_node)
845
+ elif len(keypath) == 1 and isinstance(keypath[0], ConvertIntKey):
846
+ where_fx_node = graph.call_function(
847
+ aten.where.Scalar,
848
+ args=(input_fx_node, 1, 0),
849
+ )
850
+ result_fx_node = generate_item(where_fx_node)
851
+ else:
852
+ raise NotImplementedError(f"Unsupported keypath: {keypath}")
853
+
854
+ result_symbol = ir_node.sym
855
+ result_buffer = SymbolBuffer(result_symbol)
856
+ self._record_allocation(result_buffer, result_fx_node)
857
+ self._generate_size_proxy(result_fx_node, result_symbol)
858
+
859
+ def _generate_enter_device_context_manager(self, line: WrapperLine) -> None:
860
+ if not isinstance(line, EnterDeviceContextManagerLine):
861
+ raise AssertionError(
862
+ f"expected EnterDeviceContextManagerLine, got {type(line)}"
863
+ )
864
+ # We ignore the device context in FX IR.
865
+
866
+ def _generate_exit_device_context_manager(self, line: WrapperLine) -> None:
867
+ if not isinstance(line, ExitDeviceContextManagerLine):
868
+ raise AssertionError(
869
+ f"expected ExitDeviceContextManagerLine, got {type(line)}"
870
+ )
871
+ # We ignore the device context in FX IR.
872
+
873
+ def _generate_enter_subgraph(self, line: WrapperLine) -> None:
874
+ if not isinstance(line, EnterSubgraphLine):
875
+ raise AssertionError(f"expected EnterSubgraphLine, got {type(line)}")
876
+ # We ignore memory planning lines in FX IR.
877
+
878
+ def _generate_exit_subgraph(self, line: WrapperLine) -> None:
879
+ if not isinstance(line, ExitSubgraphLine):
880
+ raise AssertionError(f"expected ExitSubgraphLine, got {type(line)}")
881
+ # We ignore memory planning lines in FX IR.
882
+
883
+ def _generate_free(self, line: WrapperLine) -> None:
884
+ if not isinstance(line, FreeLine):
885
+ raise AssertionError(f"expected FreeLine, got {type(line)}")
886
+
887
+ buf = line.node
888
+
889
+ # No need to free placeholders.
890
+ if self.buffer_to_node[buf.get_name()].op == "placeholder":
891
+ return
892
+
893
+ self._free(buf)
894
+
895
+ def _generate_free_if_not_reused(self, line: WrapperLine) -> None:
896
+ if not isinstance(line, FreeIfNotReusedLine):
897
+ raise AssertionError(f"expected FreeIfNotReusedLine, got {type(line)}")
898
+ buf = line.node
899
+ if buf.get_name() in V.graph.removed_buffers:
900
+ raise AssertionError(f"buffer {buf.get_name()} is in removed_buffers")
901
+ if not line.is_reused:
902
+ self._free(buf)
903
+
904
+ def _generate_line_context(self, line: WrapperLine) -> None:
905
+ if not isinstance(line, LineContext):
906
+ raise AssertionError(f"expected LineContext, got {type(line)}")
907
+ # We ignore line context in FX IR.
908
+
909
+ def _generate_reinterpret(self, line: WrapperLine) -> None:
910
+ if not isinstance(line, ReinterpretLine):
911
+ raise AssertionError(f"expected ReinterpretLine, got {type(line)}")
912
+ self._generate_reinterpret_helper(line.node, line.reused_as, line.layout)
913
+
914
+ def _generate_reinterpret_helper(
915
+ self, input_buffer: BufferLike, result_buffer: BufferLike, layout: ir.Layout
916
+ ) -> None:
917
+ input_node = self.buffer_to_node[input_buffer.get_name()]
918
+
919
+ # Look up output metadata.
920
+ name = result_buffer.get_name()
921
+ if not name:
922
+ raise AssertionError(f"result_buffer has an empty name: {result_buffer}")
923
+ size = tuple(layout.size)
924
+ stride = tuple(layout.stride)
925
+ if isinstance(layout, ir.NonOwningLayout):
926
+ # Look up the view's layout.
927
+ view = layout.view
928
+ if not isinstance(view, ir.ReinterpretView):
929
+ raise AssertionError(f"unexpected type: {type(view)}")
930
+ layout = view.layout
931
+ offset = input_buffer.get_offset() + layout.offset
932
+
933
+ # Map ReinterpretView to as_strided.
934
+ result_node = self._create_as_strided(input_node, size, stride, offset)
935
+ result_node.name = name
936
+ self._record_allocation(result_buffer, result_node)
937
+
938
+ def _generate_reuse(self, line: WrapperLine) -> None:
939
+ if not isinstance(line, ReuseLine):
940
+ raise AssertionError(f"expected ReuseLine, got {type(line)}")
941
+ old = line.node
942
+ new = line.reused_as
943
+ if any(buf.get_name() in V.graph.removed_buffers for buf in (old, new)):
944
+ raise AssertionError("old or new buffer is in removed_buffers")
945
+ if old.get_dtype() != new.get_dtype():
946
+ raise AssertionError(
947
+ f"dtype mismatch: {old.get_dtype()} != {new.get_dtype()}"
948
+ )
949
+
950
+ old_node = self.buffer_to_node[old.get_name()]
951
+ result_node = old_node
952
+
953
+ # Change shape and stride.
954
+ size = tuple(new.get_size())
955
+ stride = tuple(new.get_stride())
956
+ offset = new.get_offset()
957
+ if (
958
+ tuple(old.get_size()) != size
959
+ or tuple(old.get_stride()) != stride
960
+ or old.get_offset() != offset
961
+ ):
962
+ result_node = self._create_as_strided(old_node, size, stride, offset)
963
+
964
+ self._record_allocation(new, result_node)
965
+
966
+ # Free the old buffer, if we allocated a new tensor.
967
+ if (
968
+ old.get_name() not in V.graph.get_output_names()
969
+ and line.delete_old
970
+ and result_node is not old_node
971
+ ):
972
+ self._free(old)
973
+
974
+ def _generate_multi_output(self, line: WrapperLine) -> None:
975
+ if not isinstance(line, MultiOutputLine):
976
+ raise AssertionError(f"expected MultiOutputLine, got {type(line)}")
977
+
978
+ arg_node = self.buffer_to_node[line.arg_name]
979
+
980
+ # For non-tuple / non-list outputs, map the
981
+ # output to the same node as the input.
982
+ if len(line.indices) == 0:
983
+ self.buffer_to_node[line.result_name] = arg_node
984
+ return
985
+
986
+ # Extract the index for tuple access.
987
+ inds = line.indices[0][1:]
988
+ if len(inds) != 1:
989
+ raise AssertionError(f"Cannot convert {inds} to an index.")
990
+ idx = inds[0]
991
+
992
+ node = self.gm.graph.call_function(operator.getitem, args=(arg_node, idx))
993
+ node.name = line.result_name
994
+ self.buffer_to_node[line.result_name] = node
995
+
996
+ def _generate_fallback_call(
997
+ self,
998
+ ir_node: ir.ExternKernel,
999
+ args: tuple[Any, ...] | None = None,
1000
+ kwargs: dict[str, Any] | None = None,
1001
+ ) -> None:
1002
+ fx_node = self.gm.graph.call_function(
1003
+ ir_node.op_overload, # type: ignore[arg-type]
1004
+ args=args,
1005
+ kwargs=kwargs,
1006
+ )
1007
+ result_buffer = ir_node.codegen_reference()
1008
+ self.buffer_to_node[result_buffer] = fx_node
1009
+ # For in-place mutation ops (e.g., scatter_reduce_, index_put_),
1010
+ # update the buffer mapping for mutated inputs so downstream
1011
+ # references to the mutated buffer see the post-mutation node.
1012
+ for mutated_name in ir_node.get_mutation_names():
1013
+ self.buffer_to_node[mutated_name] = fx_node
1014
+
1015
+ def _generate_index_put_fallback(self, line: WrapperLine) -> None:
1016
+ if not isinstance(line, IndexPutFallbackLine):
1017
+ raise AssertionError(f"expected IndexPutFallbackLine, got {type(line)}")
1018
+ ir_node = line.node
1019
+
1020
+ def generate_buffer_or_none(
1021
+ x: ir.IRNode | Sequence[ir.IRNode] | None,
1022
+ ) -> torch.fx.Node | None:
1023
+ """
1024
+ Handles None before calling _generate_buffer.
1025
+ """
1026
+ if x is None:
1027
+ return None
1028
+
1029
+ if not isinstance(x, ir.IRNode):
1030
+ raise AssertionError(f"expected ir.IRNode, got {type(x)}")
1031
+ return self._generate_buffer(x)
1032
+
1033
+ (x, values) = [generate_buffer_or_none(t) for t in ir_node.inputs[:2]]
1034
+ indices = tuple(generate_buffer_or_none(t) for t in line.indices)
1035
+ accumulate = ir_node.constant_args[0]
1036
+ args = (x, indices, values, accumulate)
1037
+ self._generate_fallback_call(ir_node, args)
1038
+
1039
+ def _generate_scatter_fallback(self, line: WrapperLine) -> None:
1040
+ if not isinstance(line, ScatterFallbackLine):
1041
+ raise AssertionError(f"expected ScatterFallbackLine, got {type(line)}")
1042
+ ir_node = line.node
1043
+ if not ir.is_node_sequence(ir_node.inputs):
1044
+ raise AssertionError("ir_node.inputs is not a node sequence")
1045
+ (x, index, src) = [self._generate_buffer(t) for t in ir_node.inputs] + (
1046
+ [] if ir_node.src_is_tensor else [ir_node.constant_args[1]]
1047
+ )
1048
+ args = (x, ir_node.constant_args[0], index, src)
1049
+ kwargs = {}
1050
+ if reduce := ir_node.kwargs.get("reduce"):
1051
+ kwargs["reduce"] = reduce
1052
+ # Only pass kwargs that the op's schema actually accepts, since
1053
+ # ScatterFallback stores both reduce and include_self for all
1054
+ # scatter variants, but not all ops support them (e.g.,
1055
+ # scatter_.value has no kwargs, scatter_reduce_.two has both).
1056
+ if not isinstance(ir_node.op_overload, torch._ops.OpOverload):
1057
+ raise AssertionError(
1058
+ f"expected torch._ops.OpOverload, got {type(ir_node.op_overload)}"
1059
+ )
1060
+ schema_arg_names = OrderedSet(
1061
+ [a.name for a in ir_node.op_overload._schema.arguments]
1062
+ )
1063
+ kwargs = {k: v for k, v in ir_node.kwargs.items() if k in schema_arg_names}
1064
+
1065
+ self._generate_fallback_call(ir_node, args, kwargs)
1066
+
1067
+ def _generate_null(self, line: WrapperLine) -> None:
1068
+ if not isinstance(line, NullLine):
1069
+ raise AssertionError(f"expected NullLine, got {type(line)}")
1070
+ # Does nothing.
1071
+
1072
+ def _generate_comm_buffer_allocate(self, line: WrapperLine) -> None:
1073
+ if not (isinstance(line, AllocateLine) and line.comm_buffer):
1074
+ raise AssertionError("expected AllocateLine with comm_buffer set")
1075
+ raise NotImplementedError("Comm buffer allocation is not yet supported")
1076
+
1077
+ def _generate_comm_buffer_free(self, line: WrapperLine) -> None:
1078
+ if not (isinstance(line, FreeIfNotReusedLine) and line.comm_buffer):
1079
+ raise AssertionError("expected FreeIfNotReusedLine with comm_buffer set")
1080
+ self._free(line.node)
1081
+
1082
+ def _generate_triton_call(self, line: WrapperLine) -> None:
1083
+ if not isinstance(line, KernelCallLine):
1084
+ raise AssertionError(f"expected KernelCallLine, got {type(line)}")
1085
+
1086
+ # Collect all kwargs, including autotuned block sizes.
1087
+ call_args = self._lookup_args(line.call_args)
1088
+ kernel = self.kernels[line.kernel_name]
1089
+ tuner = kernel.tuner
1090
+
1091
+ def tune_kernel(tuner: CachingAutotuner, call_args: Sequence[Any]) -> None:
1092
+ from triton.runtime import driver
1093
+
1094
+ log.info("Autotuning Triton kernel %s at compile time.", kernel_name)
1095
+
1096
+ device = driver.active.get_current_device()
1097
+
1098
+ stream = driver.active.get_current_stream(device)
1099
+
1100
+ def node_to_tuning_arg(arg: Any) -> Any:
1101
+ """
1102
+ Create real tensors for autotuning arguments, substituting size hints
1103
+ for dynamic shapes.
1104
+ """
1105
+
1106
+ def to_size_hint_sympy_int(arg: sympy.Expr | int) -> int:
1107
+ return V.graph.sizevars.optimization_hint(arg)
1108
+
1109
+ def to_size_hint_list(arg: list[torch.SymInt | int]) -> list[int]:
1110
+ args_sympy = [
1111
+ x.node.expr if isinstance(x, torch.SymInt) else x for x in arg
1112
+ ]
1113
+ return pytree.tree_map(to_size_hint_sympy_int, args_sympy)
1114
+
1115
+ if not isinstance(arg, torch.fx.Node):
1116
+ return to_size_hint_sympy_int(arg)
1117
+
1118
+ fake = arg.meta["val"]
1119
+ return torch.empty_strided(
1120
+ to_size_hint_list(fake.shape),
1121
+ to_size_hint_list(fake.stride()),
1122
+ dtype=fake.dtype,
1123
+ device=device,
1124
+ ).zero_()
1125
+
1126
+ # call args can be fx nodes or sympy expressions or integers!
1127
+ arg_values = [node_to_tuning_arg(arg) for arg in call_args]
1128
+ tuner.run(*arg_values, stream=stream)
1129
+
1130
+ # Optionally autotune the kernels.
1131
+ # The FX backend currently only supports compile-time tuning.
1132
+ kernel_name = tuner.fn.__name__
1133
+ if config.triton.autotune_at_compile_time:
1134
+ # Skip compile-time autotuning if any unbacked symbol lacks a user-provided
1135
+ # optimization hint — autotuning with the generic fallback would
1136
+ # produce meaningless results.
1137
+ hinted = V.graph.sizevars.all_unbacked_explicitly_hinted
1138
+ can_tune = True
1139
+ for arg in call_args:
1140
+ if isinstance(arg, torch.fx.Node):
1141
+ fake = arg.meta["val"]
1142
+ if not hinted(list(fake.shape) + list(fake.stride())):
1143
+ can_tune = False
1144
+ break
1145
+ elif not hinted(arg):
1146
+ can_tune = False
1147
+ break
1148
+ if can_tune:
1149
+ tune_kernel(tuner, call_args)
1150
+ else:
1151
+ log.info(
1152
+ "Detected unhinted unbacked symints. Skipping compile-time autotuning for kernel %s.",
1153
+ kernel_name,
1154
+ )
1155
+ else:
1156
+ log.info(
1157
+ "Skipping autotuning for kernel %s. Set config.triton.autotune_at_compile_time = True to enable.",
1158
+ kernel_name,
1159
+ )
1160
+
1161
+ triton_meta = tuner.triton_meta
1162
+ signature = triton_meta["signature"]
1163
+
1164
+ def add_constants_to_call_args(
1165
+ call_args: Sequence[Any], cfg: Config
1166
+ ) -> tuple[Any, ...]:
1167
+ """
1168
+ Add constant kwargs to the arg list.
1169
+ """
1170
+ # Add args from the proper Triton signature.
1171
+ # Exclude constants and config kwargs, as those are tracked separately.
1172
+ new_call_args = []
1173
+ constants = triton_meta["constants"]
1174
+ call_kwargs = {
1175
+ key: val
1176
+ for key, val in zip(signature, call_args)
1177
+ # pyrefly: ignore [missing-attribute]
1178
+ if key not in constants and key not in cfg.kwargs
1179
+ }
1180
+
1181
+ # Add constants stored as Triton metadata, in signature order.
1182
+ call_kwargs |= constants
1183
+ new_call_args = [
1184
+ call_kwargs[key]
1185
+ for key in signature
1186
+ # pyrefly: ignore [missing-attribute]
1187
+ if key not in cfg.kwargs
1188
+ ]
1189
+
1190
+ # Add Inductor's extra launcher args to the end.
1191
+ if extra_launcher_args := tuner.inductor_meta.get("extra_launcher_args"):
1192
+ new_call_args.extend(
1193
+ call_args[len(call_args) - len(extra_launcher_args) :]
1194
+ )
1195
+
1196
+ return tuple(new_call_args)
1197
+
1198
+ kernel_config = tuner.compile_results[0].config
1199
+ extra_options = getattr(kernel_config, "extra_options", None)
1200
+ call_args = add_constants_to_call_args(call_args, kernel_config)
1201
+ call_args, grid = tuner._interpret_args_grid(call_args, kernel_config)
1202
+ call_kwargs = dict(zip(signature, call_args))
1203
+ # pyrefly: ignore [missing-attribute]
1204
+ if any(kwarg in kernel_config.kwargs for kwarg in call_kwargs):
1205
+ raise AssertionError(f"kwargs overlap config: {call_kwargs}")
1206
+ # pyrefly: ignore [missing-attribute]
1207
+ call_kwargs.update(kernel_config.kwargs)
1208
+
1209
+ # Replace sympy.floor with FloorDiv, to make the expression traceable.
1210
+ grid = [replace_floor_div(x) if isinstance(x, sympy.Expr) else x for x in grid]
1211
+ wrapper_grid = [tuple(self._generate_sym_nodes(grid))]
1212
+ call_kwargs = {
1213
+ name: self._generate_sym_node(val) for name, val in call_kwargs.items()
1214
+ }
1215
+ backend_options = triton_meta.get("backend_options", {})
1216
+ if backend_options:
1217
+ # FXIR executes Triton kernels through the HOP, not the already
1218
+ # materialized CachingAutotuner launcher. Preserve backend option
1219
+ # values in the HOP payload so a direct FXIR run or later Inductor
1220
+ # re-lowering re-enters Triton JIT with the same compiler options
1221
+ # that were used during FXIR precompile/autotune.
1222
+ for name, value in backend_options.items():
1223
+ # If the backend option is also a kernel parameter, call_kwargs
1224
+ # already contains the launch value reconstructed from the Triton
1225
+ # signature/config. Keep that value and only add backend options
1226
+ # that are not otherwise represented in the HOP payload.
1227
+ call_kwargs.setdefault(name, value)
1228
+
1229
+ # Store non-graphable kwargs in the side table.
1230
+ (
1231
+ call_kwargs,
1232
+ constant_args_idx,
1233
+ ) = tracing_triton_hopifier_singleton.store_non_graphable_args(call_kwargs)
1234
+
1235
+ hop_kwargs: dict[str, Any] = {
1236
+ "kernel_idx": kernel.wrapped.kernel_idx,
1237
+ "constant_args_idx": constant_args_idx,
1238
+ "grid": wrapper_grid,
1239
+ "tma_descriptor_metadata": {},
1240
+ "kwargs": call_kwargs,
1241
+ }
1242
+ if backend_options:
1243
+ # Keep the FXIR HOP call shape unchanged for normal Inductor
1244
+ # kernels. Some downstream HOP py_impls have fixed keyword-only
1245
+ # signatures and only need launch_kwargs when there are real
1246
+ # Triton backend options to preserve.
1247
+ hop_kwargs["launch_kwargs"] = tuple(backend_options)
1248
+
1249
+ triton_node = self.gm.graph.call_function(
1250
+ triton_kernel_wrapper_mutation,
1251
+ kwargs=hop_kwargs,
1252
+ )
1253
+ if extra_options:
1254
+ triton_node.meta["extra_options"] = extra_options
1255
+
1256
+ def _generate_extern_kernel_alloc(self, line: WrapperLine) -> None:
1257
+ if not isinstance(line, ExternKernelAllocLine):
1258
+ raise AssertionError(f"expected ExternKernelAllocLine, got {type(line)}")
1259
+ node = line.node
1260
+ self._generate_extern_kernel_common(node, node)
1261
+
1262
+ def _generate_extern_kernel_out(
1263
+ self,
1264
+ line: WrapperLine,
1265
+ ) -> None:
1266
+ if not isinstance(line, ExternKernelOutLine):
1267
+ raise AssertionError(f"expected ExternKernelOutLine, got {type(line)}")
1268
+ node = line.node
1269
+ out_node = node.output_view if node.output_view else node
1270
+ self._generate_extern_kernel_common(node, out_node)
1271
+
1272
+ def _generate_extern_kernel_common(
1273
+ self, kernel: ir.ExternKernel, out_ir_node: ir.IRNode
1274
+ ) -> None:
1275
+ """
1276
+ Generates FX IR from either ExternKernelAlloc or ExternKernelOut.
1277
+ """
1278
+
1279
+ # Get FX nodes corresponding to the call args.
1280
+ if not ir.is_node_sequence(kernel.inputs):
1281
+ raise AssertionError("kernel.inputs is not a node sequence")
1282
+ tensor_nodes = tuple(self._generate_buffer(arg) for arg in kernel.inputs)
1283
+ if hasattr(kernel, "unflatten_args"):
1284
+ args, _ = kernel.unflatten_args(tensor_nodes, kernel.constant_args)
1285
+ else:
1286
+ args = tensor_nodes + tuple(kernel.constant_args)
1287
+
1288
+ # Get the result buffer.
1289
+ # Some kernels write to a pre-existing output tensor via the "out" kwarg.
1290
+ # Materialize any IR nodes in kwargs to FX nodes (e.g., TensorBox -> Tensor).
1291
+ kwargs = {
1292
+ k: self._generate_buffer(v) if isinstance(v, ir.IRNode) else v
1293
+ for k, v in kernel.kwargs.items()
1294
+ }
1295
+
1296
+ result_buffer: str | None = None
1297
+ if isinstance(kernel, ir.ExternKernelOut):
1298
+ kwargs["out"] = self.buffer_to_node[out_ir_node.codegen_reference()]
1299
+ elif isinstance(kernel.layout, (ir.Layout, ir.MultiOutputLayout)):
1300
+ result_buffer = kernel.get_name()
1301
+ elif isinstance(kernel.layout, ir.NoneLayout):
1302
+ pass
1303
+ else:
1304
+ raise NotImplementedError(f"Unrecognized output layout: {kernel.layout}")
1305
+
1306
+ fx_node = self.gm.graph.call_function(
1307
+ kernel.op_overload, # type: ignore[arg-type]
1308
+ args=args,
1309
+ kwargs=kwargs,
1310
+ )
1311
+
1312
+ # Assign the result to the given name.
1313
+ if result_buffer:
1314
+ if "out" in kwargs:
1315
+ raise AssertionError(
1316
+ f"Extern kernel '{kernel}' has both result and out kwarg. Expected only one."
1317
+ )
1318
+ fx_node.name = result_buffer
1319
+ self.buffer_to_node[result_buffer] = fx_node
1320
+
1321
+ def _generate_kernel_call(self, line: WrapperLine) -> None:
1322
+ if not isinstance(line, KernelCallLine):
1323
+ raise AssertionError(f"expected KernelCallLine, got {type(line)}")
1324
+ if not line.triton:
1325
+ raise NotImplementedError("FX conversion only supports Triton kernels.")
1326
+
1327
+ self._generate_triton_call(line)
1328
+
1329
+ def _generate_kernel_definition(self, line: WrapperLine) -> None:
1330
+ if not isinstance(line, KernelDefinitionLine):
1331
+ raise AssertionError(f"expected KernelDefinitionLine, got {type(line)}")
1332
+
1333
+ # Generate code for the kernel.
1334
+ kernel_code = PythonWrapperCodegen._format_kernel_definition(
1335
+ line.kernel_name, line.kernel_body, metadata=line.metadata
1336
+ )
1337
+
1338
+ # Import the module and store the JIT kernel.
1339
+ tuner = self._import_kernel(kernel_code, line.kernel_name)
1340
+ wrapped = wrap_triton(tuner.fn)
1341
+ self.kernels[line.kernel_name] = TritonKernel(tuner, wrapped)
1342
+
1343
+ def _generate_symbolic_call_arg(self, line: WrapperLine) -> None:
1344
+ if not isinstance(line, SymbolicCallArgLine):
1345
+ raise AssertionError(f"expected SymbolicCallArgLine, got {type(line)}")
1346
+ # Store the arg: expr mapping for later use.
1347
+ arg = line.arg
1348
+
1349
+ inner_expr_proxy = self._sympy_interp(arg.inner_expr)
1350
+ self.expr_to_proxy[arg.inner] = inner_expr_proxy
1351
+
1352
+ def _generate_unbacked_symbol_defs(self, line: WrapperLine) -> None:
1353
+ if not isinstance(line, UnbackedSymbolDefsLine):
1354
+ raise AssertionError(f"expected UnbackedSymbolDefsLine, got {type(line)}")
1355
+ graph = self.gm.graph
1356
+
1357
+ def convert_key(node: torch.fx.Node, path: pytree.KeyPath) -> torch.fx.Node:
1358
+ """
1359
+ Generate FX IR for each key entry.
1360
+ """
1361
+ # Base case.
1362
+ if len(path) == 0:
1363
+ return node
1364
+
1365
+ # Process the first entry and recurse.
1366
+ entry = path[0]
1367
+ if isinstance(entry, CallMethodKey):
1368
+ target = {
1369
+ "size": aten.sym_size.int,
1370
+ "stride": aten.sym_stride.int,
1371
+ "storage_offset": aten.sym_storage_offset,
1372
+ }[entry.name]
1373
+ if not callable(target):
1374
+ raise AssertionError(f"target is not callable: {target}")
1375
+ node = graph.call_function(
1376
+ target,
1377
+ args=(
1378
+ (node, path[1].idx)
1379
+ if len(path) > 1 and isinstance(path[1], pytree.SequenceKey)
1380
+ else (node,)
1381
+ ),
1382
+ )
1383
+ return convert_key(node, path[1 + len(node.args) :])
1384
+ elif isinstance(entry, pytree.SequenceKey):
1385
+ node = graph.call_function(operator.getitem, args=(node, entry.idx))
1386
+ return convert_key(node, path[1:])
1387
+ elif isinstance(entry, DivideByKey):
1388
+ node = graph.call_function(
1389
+ operator.floordiv, args=(node, entry.divisor)
1390
+ )
1391
+ return convert_key(node, path[1:])
1392
+ else:
1393
+ raise NotImplementedError(f"Unrecognized entry type: {type(entry)}")
1394
+
1395
+ unbacked_bindings = line.unbacked_bindings
1396
+ if unbacked_bindings is None:
1397
+ raise AssertionError("line.unbacked_bindings must not be None")
1398
+ # Kernels with no unbacked symbols aren't recorded in buffer_to_node, so
1399
+ # return before the output-buffer lookup to avoid a KeyError. Mirrors
1400
+ # the non-FX wrapper's early return.
1401
+ if not unbacked_bindings:
1402
+ return
1403
+ root_node = self.buffer_to_node[line.output_name]
1404
+ for s, keypath in unbacked_bindings.items():
1405
+ # Check if we already generated this symbol.
1406
+ if s.name in self.buffer_to_node:
1407
+ continue
1408
+
1409
+ node = convert_key(root_node, keypath)
1410
+ out_buffer = SymbolBuffer(s)
1411
+ self._record_allocation(out_buffer, node)
1412
+ self._generate_size_proxy(node, s)
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__init__.py ADDED
File without changes
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (202 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/compile_utils.cpython-312.pyc ADDED
Binary file (5.56 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/device_op_overrides.cpython-312.pyc ADDED
Binary file (4.23 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_combined_scheduling.cpython-312.pyc ADDED
Binary file (7.61 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/__pycache__/xpu_env.cpython-312.pyc ADDED
Binary file (1.6 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/compile_utils.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import functools
3
+ import logging
4
+ import os
5
+ import shutil
6
+ import subprocess
7
+
8
+ from torch._inductor import config
9
+ from torch._inductor.codegen.xpu.xpu_env import get_xpu_arch
10
+ from torch._inductor.utils import is_linux
11
+
12
+ from ..cuda.compile_utils import _cutlass_include_paths
13
+
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
18
+ @functools.cache
19
+ def icpx_exist(icpx_path: str | None = "icpx") -> bool:
20
+ return icpx_path is not None and shutil.which(icpx_path) is not None
21
+
22
+
23
+ def _sycl_compiler() -> str:
24
+ # Search order:
25
+ # 0) which icpx
26
+ # 1) config.xpu.oneapi_root
27
+ # 2) ONEAPI_ROOT environment variable
28
+ # 3) default system search PATH.
29
+ if icpx_exist("icpx"):
30
+ return "icpx"
31
+
32
+ if os.path.exists(config.xpu.oneapi_root or ""):
33
+ oneapi_root = config.xpu.oneapi_root
34
+ elif os.path.exists(os.getenv("ONEAPI_ROOT") or ""):
35
+ oneapi_root = os.getenv("ONEAPI_ROOT")
36
+ else:
37
+ oneapi_root = None
38
+
39
+ if oneapi_root:
40
+ oneapi_inclue = os.path.join(oneapi_root, "include")
41
+ if "CPLUS_INCLUDE_PATH" in os.environ:
42
+ os.environ["CPLUS_INCLUDE_PATH"] += ":" + oneapi_inclue
43
+ else:
44
+ os.environ["CPLUS_INCLUDE_PATH"] = oneapi_inclue
45
+ return os.path.realpath(os.path.join(oneapi_root, "bin/icpx"))
46
+
47
+ # Mirrors _cuda_compiler(): return the bare name and let the compile
48
+ # subprocess produce the error, so callers can probe with icpx_exist().
49
+ return "icpx"
50
+
51
+
52
+ def _sycl_lib_options() -> list[str]:
53
+ """
54
+ Util function for CUTLASS backend to find the correct XPU libraries.
55
+ """
56
+ # _set_gpu_runtime_env() # cpp_extension consults the env
57
+ from torch.utils import cpp_extension
58
+
59
+ lpaths = cpp_extension.library_paths(device_type="xpu")
60
+ extra_ldflags: list[str] = []
61
+ if is_linux():
62
+ for path in lpaths:
63
+ if "torch/lib" in path:
64
+ # don't want to depend on pytorch
65
+ continue
66
+ # -rpath ensures the DLL can find its dependencies when loaded, even
67
+ # if the library path is non-standard.
68
+ extra_ldflags.extend([f"-L{path}", "-Xlinker", f"-rpath={path}"])
69
+
70
+ extra_ldflags.append("-lsycl")
71
+ else:
72
+ raise NotImplementedError(
73
+ "Unsupported env, failed to find xpu libs! Currently only Linux is supported."
74
+ )
75
+ return extra_ldflags
76
+
77
+
78
+ def _sycl_arch_as_compile_option() -> str:
79
+ arc_option_map = {"Xe12": "pvc", "Xe20": "bmg-g21,bmg-g31"}
80
+ arch = get_xpu_arch()
81
+ return arc_option_map.get(arch, "pvc")
82
+
83
+
84
+ def _sycl_compiler_options() -> list[str]:
85
+ options = [
86
+ "-DCUTLASS_ENABLE_SYCL",
87
+ "-DSYCL_INTEL_TARGET",
88
+ "-DCUTLASS_VERSIONS_GENERATED",
89
+ "-O3",
90
+ "-DNDEBUG",
91
+ "-std=c++20",
92
+ "-fPIC",
93
+ "-fsycl",
94
+ "-fsycl-targets=spir64_gen",
95
+ "-Xspirv-translator",
96
+ "-spirv-ext=+SPV_INTEL_split_barrier,+SPV_INTEL_2d_block_io,+SPV_INTEL_subgroup_matrix_multiply_accumulate",
97
+ "-fno-sycl-instrument-device-code",
98
+ "-DMKL_ILP64",
99
+ "-MD",
100
+ "-Xs",
101
+ (
102
+ f"-device {_sycl_arch_as_compile_option()} "
103
+ "-options \"-igc_opts 'VISAOptions=-perfmodel,VectorAliasBBThreshold=100000000000,"
104
+ "ExtraOCLOptions=-cl-intel-256-GRF-per-thread'\" "
105
+ "-options -ze-opt-large-register-file"
106
+ ),
107
+ ]
108
+ if config.cutlass.enable_debug_info:
109
+ options.extend(["-lineinfo", "-g", "-DCUTLASS_DEBUG_TRACE_LEVEL=1"])
110
+ return options
111
+
112
+
113
+ def xpu_compile_command(
114
+ src_files: list[str],
115
+ dst_file: str,
116
+ dst_file_ext: str,
117
+ extra_args: list[str] | None = None,
118
+ ) -> str:
119
+ if extra_args is None:
120
+ extra_args = []
121
+ include_paths = _cutlass_include_paths()
122
+ sycl_lib_options = _sycl_lib_options()
123
+ sycl_compiler_options = _sycl_compiler_options()
124
+
125
+ # Build command as a list to preserve arguments with spaces
126
+ cmd_parts = (
127
+ [_sycl_compiler()]
128
+ + extra_args
129
+ + ["-I" + path for path in include_paths]
130
+ + ["-isystem", "/include"]
131
+ + sycl_compiler_options
132
+ + sycl_lib_options
133
+ )
134
+ if dst_file_ext == "o":
135
+ cmd_parts.extend(["-c", "-o", dst_file] + src_files)
136
+ elif dst_file_ext == "so":
137
+ cmd_parts.extend(["-shared", "-o", dst_file] + src_files)
138
+ elif dst_file_ext == "exe":
139
+ cmd_parts.extend(["-o", dst_file] + src_files)
140
+ else:
141
+ raise NotImplementedError(f"Unsupported output file suffix {dst_file_ext}!")
142
+
143
+ res = subprocess.list2cmdline(cmd_parts)
144
+ log.debug("XPU command: %s", res)
145
+ return res
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/device_op_overrides.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from ..common import (
4
+ DeviceIdx,
5
+ DeviceOpOverrides,
6
+ register_device_op_overrides,
7
+ TritonScratchWorkspace,
8
+ )
9
+
10
+
11
+ class XPUDeviceOpOverrides(DeviceOpOverrides):
12
+ def import_get_raw_stream_as(self, name: str) -> str:
13
+ return f"from torch._C import _xpu_getCurrentRawStream as {name}"
14
+
15
+ def set_device(self, device_idx: DeviceIdx) -> str:
16
+ return f"torch.xpu.set_device({device_idx})"
17
+
18
+ def synchronize(self) -> str:
19
+ return "torch.xpu.synchronize()"
20
+
21
+ def device_guard(self, device_idx: DeviceIdx) -> str:
22
+ return f"torch.xpu._DeviceGuard({device_idx})"
23
+
24
+ def current_device_idx_expr(self) -> str:
25
+ return "torch.xpu.current_device()"
26
+
27
+ def current_stream(self) -> str:
28
+ return "torch.xpu.current_stream()"
29
+
30
+ def cpp_device_guard(self) -> str:
31
+ return "at::DeviceGuard"
32
+
33
+ def cpp_aoti_device_guard(self) -> str:
34
+ return "AOTIXpuGuard"
35
+
36
+ def cpp_stream_guard(self) -> str:
37
+ return "at::xpu::XPUStreamGuard"
38
+
39
+ def cpp_aoti_stream_guard(self) -> str:
40
+ return "AOTIXpuStreamGuard"
41
+
42
+ def cpp_getStreamFromExternal(self) -> str:
43
+ return "at::xpu::getStreamFromExternal"
44
+
45
+ def kernel_header(self) -> str:
46
+ source_codes = """
47
+ #include <torch/csrc/inductor/aoti_runtime/sycl_runtime_wrappers.h>
48
+ """
49
+ return source_codes
50
+
51
+ def kernel_driver(self) -> str:
52
+ return ""
53
+
54
+ def cpp_stream_type(self) -> str:
55
+ return "sycl::queue*"
56
+
57
+ def aoti_get_stream(self) -> str:
58
+ return "aoti_torch_get_current_xpu_stream"
59
+
60
+ def cpp_kernel_type(self) -> str:
61
+ return "std::unique_ptr<sycl::kernel>"
62
+
63
+ def cpp_device_ptr(self) -> str:
64
+ return "void *"
65
+
66
+ def cpp_scratch(
67
+ self, idx: int, workspace: TritonScratchWorkspace, prefix: str | None = None
68
+ ) -> tuple[list[str], str] | None:
69
+ return [f"void *global_scratch_{idx} = 0;"], f"global_scratch_{idx}"
70
+
71
+
72
+ register_device_op_overrides("xpu", XPUDeviceOpOverrides())
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_combined_scheduling.py ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, TYPE_CHECKING
5
+
6
+ from torch._inductor.scheduler import (
7
+ BaseSchedulerNode,
8
+ BaseScheduling,
9
+ FusedSchedulerNode,
10
+ Scheduler,
11
+ SchedulerNode,
12
+ )
13
+
14
+ from ..cutlass.scheduling import CUTLASSScheduling
15
+ from ..triton import TritonScheduling
16
+
17
+
18
+ if TYPE_CHECKING:
19
+ from collections.abc import Sequence
20
+ from typing import TypeAlias
21
+
22
+ from sympy import Expr
23
+
24
+ import torch
25
+ from torch.utils._ordered_set import OrderedSet
26
+
27
+ from ..common import BackendFeature
28
+
29
+ _IntLike: TypeAlias = int | Expr
30
+
31
+
32
+ class XPUCombinedScheduling(BaseScheduling):
33
+ """
34
+ Scheduler for XPU Kernels, which delegates calls as appropriate
35
+ to the SYCL-C++ and Triton Schedulers, which both work for XPU devices
36
+ and use a unified-wrapper for codegen.
37
+
38
+ If Scheduling code needs to be specialized for the case of mixed Triton / SYCL C++ code,
39
+ this would also be the place to do it.
40
+ """
41
+
42
+ def __init__(self, scheduler: Scheduler | None) -> None:
43
+ super().__init__(scheduler)
44
+ self._triton_scheduling = TritonScheduling(scheduler)
45
+ self._cutlass_scheduling = CUTLASSScheduling(scheduler)
46
+
47
+ def get_backend_features(self, device: torch.device) -> OrderedSet[BackendFeature]:
48
+ return self._triton_scheduling.get_backend_features(device)
49
+
50
+ def choose_node_backend(self, node: BaseSchedulerNode) -> BaseScheduling:
51
+ if self._cutlass_scheduling.is_cutlass_template(node):
52
+ return self._cutlass_scheduling
53
+ return self._triton_scheduling
54
+
55
+ def can_fuse_vertical(
56
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
57
+ ) -> bool:
58
+ if self._cutlass_scheduling.can_fuse_vertical(node1, node2):
59
+ return True
60
+ elif self._cutlass_scheduling.is_cutlass_template(
61
+ node1
62
+ ) or self._cutlass_scheduling.is_cutlass_template(node2):
63
+ return False
64
+ return self._triton_scheduling.can_fuse_vertical(node1, node2)
65
+
66
+ def can_fuse_horizontal(
67
+ self, node1: BaseSchedulerNode, node2: BaseSchedulerNode
68
+ ) -> bool:
69
+ for node in (node1, node2):
70
+ if self._cutlass_scheduling.is_cutlass_template(node):
71
+ return self._cutlass_scheduling.can_fuse_horizontal(
72
+ node1, node2
73
+ ) # always False at the moment
74
+ return self._triton_scheduling.can_fuse_horizontal(node1, node2)
75
+
76
+ def group_fn(
77
+ self, sizes: Sequence[Sequence[_IntLike]]
78
+ ) -> tuple[tuple[_IntLike, ...], ...]:
79
+ return self._triton_scheduling.group_fn(sizes)
80
+
81
+ def codegen_template(
82
+ self,
83
+ template_node: BaseSchedulerNode,
84
+ epilogue_nodes: Sequence[BaseSchedulerNode],
85
+ prologue_nodes: Sequence[BaseSchedulerNode],
86
+ ) -> str | None:
87
+ if self._cutlass_scheduling.is_cutlass_template(template_node):
88
+ if prologue_nodes:
89
+ raise AssertionError("cutlass template does not support prologue_nodes")
90
+ return self._cutlass_scheduling.codegen_template(
91
+ template_node, epilogue_nodes, prologue_nodes
92
+ )
93
+ else:
94
+ return self._triton_scheduling.codegen_template(
95
+ template_node, epilogue_nodes, prologue_nodes
96
+ )
97
+
98
+ def codegen_mix_order_reduction(self, node):
99
+ return self._triton_scheduling.codegen_mix_order_reduction(node)
100
+
101
+ def codegen_nested_reduction(self, node):
102
+ return self._triton_scheduling.codegen_nested_reduction(node)
103
+
104
+ def codegen_node(self, node: FusedSchedulerNode | SchedulerNode) -> None:
105
+ return self._triton_scheduling.codegen_node(node)
106
+
107
+ def codegen_sync(self) -> None:
108
+ return self._triton_scheduling.codegen_sync()
109
+
110
+ def flush(self) -> None:
111
+ return self._triton_scheduling.flush()
112
+
113
+ def codegen_combo_kernel(self, *args: Any, **kwargs: Any) -> None:
114
+ return self._triton_scheduling.codegen_combo_kernel(*args, **kwargs)
115
+
116
+ def benchmark_fused_nodes(
117
+ self, nodes: Sequence[BaseSchedulerNode]
118
+ ) -> tuple[float, str]:
119
+ return self._triton_scheduling.benchmark_fused_nodes(nodes)
120
+
121
+ def benchmark_codegened_module(self, module):
122
+ return self._triton_scheduling.benchmark_codegened_module(module)
123
+
124
+ def generate_kernel_code_from_nodes(
125
+ self,
126
+ nodes: Sequence[Any],
127
+ benchmark_kernel: bool = False,
128
+ hint_override: int | None = None,
129
+ ) -> str:
130
+ return self._triton_scheduling.generate_kernel_code_from_nodes(
131
+ nodes, benchmark_kernel, hint_override=hint_override
132
+ )
133
+
134
+ def benchmark_combo_kernel(
135
+ self, node_list: Sequence[BaseSchedulerNode], node_benchmark_results
136
+ ) -> tuple[float, float, list[str | None]]:
137
+ return self._triton_scheduling.benchmark_combo_kernel(
138
+ node_list, node_benchmark_results
139
+ )
.venv/lib/python3.12/site-packages/torch/_inductor/codegen/xpu/xpu_env.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+
4
+ import torch
5
+ from torch._inductor.utils import clear_on_fresh_cache
6
+
7
+
8
+ log = logging.getLogger(__name__)
9
+
10
+
11
+ @clear_on_fresh_cache
12
+ @functools.lru_cache(1)
13
+ def get_xpu_arch() -> str | None:
14
+ from torch.testing._internal.common_xpu import get_xpu_codename, XPUCodename
15
+
16
+ name2arch = {
17
+ XPUCodename.PVC: "Xe12",
18
+ XPUCodename.BMG: "Xe20",
19
+ }
20
+
21
+ codename = get_xpu_codename()
22
+ if not codename or codename not in name2arch:
23
+ log.warning("Unknown XPU codename, cannot determine architecture")
24
+ return None
25
+
26
+ return name2arch[codename]
27
+
28
+
29
+ @clear_on_fresh_cache
30
+ @functools.lru_cache(1)
31
+ def get_xpu_version() -> str | None:
32
+ # string of version, like 20250101
33
+ try:
34
+ xpu_version = torch.version.xpu or ""
35
+ return xpu_version
36
+ except Exception:
37
+ log.exception("Error getting xpu version")
38
+ return None
.venv/lib/python3.12/site-packages/torch/_inductor/comm_analysis.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import logging
3
+ import math
4
+ import operator
5
+ from dataclasses import dataclass
6
+ from enum import IntEnum
7
+ from typing import Any
8
+
9
+ import sympy
10
+
11
+ import torch
12
+ import torch.utils._pytree as pytree
13
+ from torch.fx.experimental.symbolic_shapes import optimization_hint
14
+ from torch.fx.operator_schemas import normalize_function
15
+
16
+ from . import ir
17
+ from .utils import get_dtype_size, snode_args_kwargs, sympy_product
18
+ from .virtualized import V
19
+
20
+
21
+ log = logging.getLogger(__name__)
22
+
23
+
24
+ class NCCL_COLL(IntEnum):
25
+ ALL_REDUCE = 0
26
+ ALL_GATHER = 1
27
+ REDUCE_SCATTER = 2
28
+ ALL_TO_ALL = 3
29
+ UNSUPPORTED = 4
30
+ P2P = 5
31
+
32
+
33
+ class NVIDIA_GPU_TYPE(IntEnum):
34
+ VOLTA = 0
35
+ AMPERE = 1
36
+ HOPPER = 2
37
+ BLACKWELL = 3
38
+
39
+
40
+ class InterconnectType(IntEnum):
41
+ NVLINK_V100 = 0
42
+ NVLINK_A100 = 1
43
+ NVLINK_H100 = 2
44
+ NVLINK_B200 = 3
45
+ IB_HDR = 4 # 200 Gbps InfiniBand
46
+ IB_NDR = 5 # 400 Gbps InfiniBand / RoCE
47
+ PCIE = 6 # PCIe (no NVLink)
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class InterconnectProfile:
52
+ """Empirically calibrated interconnect parameters for saturation estimation."""
53
+
54
+ bus_bw_GBps: float # effective bus bandwidth at large messages (GB/s)
55
+ latency_per_hop_us: float # per-ring-step latency (us)
56
+ base_latency_us: float # fixed startup latency (us)
57
+ min_saturation_bytes: int = 0 # floor for small group sizes
58
+
59
+
60
+ _MB = 1024 * 1024
61
+
62
+ # Empirically calibrated per-interconnect profiles for saturation estimation.
63
+ # NVLink bus_bw from https://github.com/NVIDIA/nccl/blob/master/src/graph/topo.h
64
+ # IB hop_lat/base_lat from MAST sweep profiles on H100 GrandTeton RoCE
65
+ # (see agent_space/nccl_model_validation.md for calibration data).
66
+ # IB min_saturation_bytes floors the estimate for small group sizes where the
67
+ # ring-step formula underestimates.
68
+ INTERCONNECT_PROFILES: dict[InterconnectType, InterconnectProfile] = {
69
+ InterconnectType.NVLINK_H100: InterconnectProfile(36.0, 40.0, 10.0),
70
+ InterconnectType.NVLINK_A100: InterconnectProfile(22.0, 45.0, 10.0),
71
+ InterconnectType.NVLINK_B200: InterconnectProfile(60.0, 30.0, 10.0),
72
+ InterconnectType.NVLINK_V100: InterconnectProfile(14.0, 50.0, 10.0),
73
+ InterconnectType.IB_NDR: InterconnectProfile(
74
+ 22.0, 12.0, 30.0, min_saturation_bytes=100 * _MB
75
+ ),
76
+ InterconnectType.IB_HDR: InterconnectProfile(
77
+ 11.0, 14.0, 30.0, min_saturation_bytes=75 * _MB
78
+ ),
79
+ # PCIe: ~10 GB/s effective NCCL bus BW (GPU->CPU->GPU ring steps)
80
+ InterconnectType.PCIE: InterconnectProfile(10.0, 60.0, 15.0),
81
+ }
82
+
83
+ _GPU_TO_INTRA: dict[NVIDIA_GPU_TYPE, InterconnectType] = {
84
+ NVIDIA_GPU_TYPE.VOLTA: InterconnectType.NVLINK_V100,
85
+ NVIDIA_GPU_TYPE.AMPERE: InterconnectType.NVLINK_A100,
86
+ NVIDIA_GPU_TYPE.HOPPER: InterconnectType.NVLINK_H100,
87
+ NVIDIA_GPU_TYPE.BLACKWELL: InterconnectType.NVLINK_B200,
88
+ }
89
+ _GPU_TO_INTER: dict[NVIDIA_GPU_TYPE, InterconnectType] = {
90
+ NVIDIA_GPU_TYPE.VOLTA: InterconnectType.IB_HDR,
91
+ NVIDIA_GPU_TYPE.AMPERE: InterconnectType.IB_HDR,
92
+ NVIDIA_GPU_TYPE.HOPPER: InterconnectType.IB_NDR,
93
+ NVIDIA_GPU_TYPE.BLACKWELL: InterconnectType.IB_NDR,
94
+ }
95
+
96
+
97
+ @functools.lru_cache
98
+ def _has_nvlink() -> bool:
99
+ """Detect NVLink via nvidia-smi topology, falling back to peer access check."""
100
+ import subprocess
101
+
102
+ if not torch.cuda.is_available() or torch.cuda.device_count() < 2:
103
+ return True # Single GPU: interconnect irrelevant
104
+ try:
105
+ result = subprocess.run(
106
+ ["nvidia-smi", "topo", "-m"],
107
+ capture_output=True,
108
+ text=True,
109
+ timeout=5,
110
+ )
111
+ if result.returncode == 0:
112
+ # Check GPU-GPU section (before Legend) for "NV" links
113
+ topo = result.stdout.split("Legend")[0]
114
+ return "NV" in topo
115
+ except (subprocess.TimeoutExpired, OSError):
116
+ pass
117
+ # Fallback: peer access generally implies NVLink on datacenter GPUs
118
+ try:
119
+ return torch.cuda.can_device_access_peer(0, 1)
120
+ except (AssertionError, RuntimeError):
121
+ return True
122
+
123
+
124
+ @functools.lru_cache
125
+ def get_gpu_type() -> NVIDIA_GPU_TYPE:
126
+ # Prefer compute capability (works for all NVIDIA GPUs, including H200, L40, etc.)
127
+ if torch.cuda.is_available() and torch.cuda.device_count() > 0:
128
+ major = torch.cuda.get_device_properties(0).major
129
+ if major >= 10:
130
+ return NVIDIA_GPU_TYPE.BLACKWELL
131
+ if major >= 9:
132
+ return NVIDIA_GPU_TYPE.HOPPER
133
+ if major >= 8:
134
+ return NVIDIA_GPU_TYPE.AMPERE
135
+ if major >= 7:
136
+ return NVIDIA_GPU_TYPE.VOLTA
137
+ # Fallback: nvidia-smi string matching
138
+ gpu_info = torch.utils.collect_env.get_gpu_info(torch.utils.collect_env.run) or ""
139
+ if "V100" in gpu_info:
140
+ return NVIDIA_GPU_TYPE.VOLTA
141
+ elif "A100" in gpu_info:
142
+ return NVIDIA_GPU_TYPE.AMPERE
143
+ elif "H100" in gpu_info:
144
+ return NVIDIA_GPU_TYPE.HOPPER
145
+ elif any(gpu in gpu_info for gpu in ("B100", "B200", "B300")):
146
+ return NVIDIA_GPU_TYPE.BLACKWELL
147
+ else:
148
+ return NVIDIA_GPU_TYPE.AMPERE
149
+
150
+
151
+ def detect_interconnect(group_size: int) -> InterconnectType:
152
+ """Auto-detect interconnect type from GPU generation and group topology."""
153
+ gpus_per_node = torch.cuda.device_count() if torch.cuda.is_available() else 8
154
+ gpu_gen = get_gpu_type()
155
+ if math.ceil(group_size / gpus_per_node) == 1:
156
+ if not _has_nvlink():
157
+ return InterconnectType.PCIE
158
+ return _GPU_TO_INTRA.get(gpu_gen, InterconnectType.NVLINK_A100)
159
+ return _GPU_TO_INTER.get(gpu_gen, InterconnectType.IB_HDR)
160
+
161
+
162
+ def get_collective_type_from_kernel_name(kernel_name: str) -> NCCL_COLL:
163
+ if kernel_name is None:
164
+ raise AssertionError("kernel_name must not be None")
165
+ if "all_reduce" in kernel_name:
166
+ return NCCL_COLL.ALL_REDUCE
167
+ elif "all_gather" in kernel_name:
168
+ return NCCL_COLL.ALL_GATHER
169
+ elif "reduce_scatter" in kernel_name:
170
+ return NCCL_COLL.REDUCE_SCATTER
171
+ elif any(comm in kernel_name for comm in ("all_to_all", "alltoall")):
172
+ return NCCL_COLL.ALL_TO_ALL
173
+ elif any(comm in kernel_name for comm in ("isend", "irecv", "batch_p2p")):
174
+ return NCCL_COLL.P2P
175
+ else:
176
+ return NCCL_COLL.UNSUPPORTED
177
+
178
+
179
+ def get_collective_type(node: ir.IRNode) -> NCCL_COLL:
180
+ if not isinstance(node, ir._CollectiveKernel):
181
+ raise ValueError(f"node is not a collective kernel: {node}")
182
+
183
+ name = node.python_kernel_name
184
+ if name is None:
185
+ raise AssertionError("node.python_kernel_name must not be None")
186
+ return get_collective_type_from_kernel_name(name)
187
+
188
+
189
+ def get_ir_node_size_numel(size: torch.Size, fallback: int = 4096 * 4096) -> int:
190
+ numel = sympy_product(size)
191
+ if isinstance(numel, sympy.Integer):
192
+ return int(numel)
193
+ return V.graph.sizevars.optimization_hint(numel, fallback=fallback)
194
+
195
+
196
+ def get_fx_node_size_numel(size: torch.Size, fallback: int = 4096 * 4096) -> int:
197
+ numel = functools.reduce(operator.mul, size, 1)
198
+ result = optimization_hint(numel, fallback=fallback)
199
+ return result
200
+
201
+
202
+ def get_collective_input_size_bytes(node: ir.IRNode) -> int:
203
+ sz_bytes = 0
204
+ for inp in node.inputs: # type: ignore[attr-defined]
205
+ numel = get_ir_node_size_numel(inp.layout.size)
206
+ sz_bytes += numel * get_dtype_size(inp.layout.dtype)
207
+ return sz_bytes
208
+
209
+
210
+ def get_collective_group_size(node: ir.IRNode) -> int:
211
+ if isinstance(node, ir._CollectiveKernel) and not isinstance(node, ir._WaitKernel):
212
+ from torch.distributed.distributed_c10d import _get_group_size_by_name
213
+
214
+ return _get_group_size_by_name(node.constant_args[-1])
215
+ else:
216
+ raise TypeError(f"Unsupported collective type: {node}")
217
+
218
+
219
+ ####################################################################################################################
220
+ # The following code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
221
+ ####################################################################################################################
222
+
223
+
224
+ class NCCL_HW(IntEnum):
225
+ NVLINK = 0
226
+ PCI = 1
227
+ NET = 2
228
+
229
+
230
+ class NCCL_ALGO(IntEnum):
231
+ TREE = 0
232
+ RING = 1
233
+
234
+
235
+ class NCCL_PROTO(IntEnum):
236
+ # Matches NCCL devcomm.h protocol enum
237
+ LL = 0 # Low-latency
238
+ LL128 = 1 # Low-latency 128-byte
239
+ SIMPLE = 2
240
+
241
+
242
+ _NUM_ALGOS = 2 # TREE, RING
243
+ _NUM_PROTOS = 3 # LL, LL128, SIMPLE
244
+
245
+ # Base latencies in us — [algo][proto]
246
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
247
+ baseLat = [
248
+ # Tree
249
+ [6.8, 14.0, 8.4],
250
+ # Ring
251
+ [6.6, 14.0, 8.4],
252
+ ]
253
+
254
+ # Hardware latencies in us — [hw][algo][proto]
255
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
256
+ hwLat = [
257
+ # NVLINK
258
+ [
259
+ [0.6, 1.25, 4.0], # Tree
260
+ [0.6, 1.9, 3.4], # Ring
261
+ ],
262
+ # PCI
263
+ [
264
+ [1.0, 1.9, 4.0], # Tree
265
+ [1.0, 2.5, 5.7], # Ring
266
+ ],
267
+ # NET
268
+ [
269
+ [5.0, 8.5, 14.0], # Tree
270
+ [2.7, 4.0, 14.0], # Ring
271
+ ],
272
+ ]
273
+
274
+
275
+ # LL max bus BW — [compCapIndex][scaleIndex(N1/N2/N4+)]
276
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
277
+ llMaxBws = [
278
+ [39.0, 39.0, 20.4], # Volta
279
+ [87.7, 22.5, 19.0], # Ampere
280
+ [141.0, 45.0, 35.0], # Hopper
281
+ [282.0, 90.0, 70.0], # Blackwell
282
+ ]
283
+
284
+ # Per-channel max BW caps — [compCapIndex][scaleIndex]
285
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
286
+ perChMaxRingLL128Bws = [
287
+ [20.0, 20.0, 20.0], # Volta
288
+ [20.0, 20.0, 20.0], # Ampere
289
+ [36.7, 36.7, 36.7], # Hopper
290
+ [40.0, 40.0, 40.0], # Blackwell
291
+ ]
292
+
293
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
294
+ perChMaxTreeLL128Bws = [
295
+ [20.0, 20.0, 20.0], # Volta
296
+ [20.0, 20.0, 20.0], # Ampere
297
+ [36.7, 36.7, 29.0], # Hopper
298
+ [55.6, 31.67, 20.0], # Blackwell
299
+ ]
300
+
301
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
302
+ perChMaxTreeBws = [
303
+ [26.5, 18.5, 10.0], # Volta
304
+ [24.0, 23.6, 17.8], # Ampere
305
+ [38.7, 41.4, 36.0], # Hopper
306
+ [70.0, 42.8, 24.0], # Blackwell
307
+ ]
308
+
309
+ # Tree correction factor for medium message sizes — [proto][logSize]
310
+ # logSize = log2(nBytes >> 6), indices 0..23 map to 64B..256MB
311
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc (ncclTunerConstantsDefaults)
312
+ treeCorrectionFactor = [
313
+ # LL
314
+ [
315
+ 1.0,
316
+ 1.0,
317
+ 1.0,
318
+ 1.0,
319
+ 0.9,
320
+ 0.8,
321
+ 0.7,
322
+ 0.7,
323
+ 0.7,
324
+ 0.7,
325
+ 0.6,
326
+ 0.5,
327
+ 0.4,
328
+ 0.4,
329
+ 0.5,
330
+ 0.6,
331
+ 0.7,
332
+ 0.8,
333
+ 0.9,
334
+ 1.0,
335
+ 1.0,
336
+ 1.0,
337
+ 1.0,
338
+ 1.0,
339
+ ],
340
+ # LL128
341
+ [
342
+ 1.0,
343
+ 1.0,
344
+ 1.0,
345
+ 1.0,
346
+ 1.0,
347
+ 0.9,
348
+ 0.8,
349
+ 0.8,
350
+ 0.8,
351
+ 0.7,
352
+ 0.6,
353
+ 0.6,
354
+ 0.6,
355
+ 0.6,
356
+ 0.6,
357
+ 0.6,
358
+ 0.8,
359
+ 0.9,
360
+ 0.9,
361
+ 0.9,
362
+ 0.9,
363
+ 1.0,
364
+ 1.0,
365
+ 1.0,
366
+ ],
367
+ # SIMPLE
368
+ [
369
+ 0.9,
370
+ 0.9,
371
+ 0.9,
372
+ 0.9,
373
+ 0.9,
374
+ 0.9,
375
+ 0.9,
376
+ 0.8,
377
+ 0.7,
378
+ 0.6,
379
+ 0.6,
380
+ 0.5,
381
+ 0.5,
382
+ 0.5,
383
+ 0.5,
384
+ 0.6,
385
+ 0.7,
386
+ 0.8,
387
+ 0.7,
388
+ 0.7,
389
+ 0.8,
390
+ 0.9,
391
+ 0.9,
392
+ 0.9,
393
+ ],
394
+ ]
395
+
396
+ # Heuristic nChannels per GPU generation.
397
+ # NCCL selects dynamically via topology search (up to MAXCHANNELS/2=32 for ring).
398
+ # These approximate standard DGX/HGX topologies; see nccl/src/graph/search.cc.
399
+ _GPU_NCHANNELS = {
400
+ NVIDIA_GPU_TYPE.VOLTA: 2,
401
+ NVIDIA_GPU_TYPE.AMPERE: 8,
402
+ NVIDIA_GPU_TYPE.HOPPER: 16,
403
+ NVIDIA_GPU_TYPE.BLACKWELL: 32,
404
+ }
405
+
406
+ # NVLink bus bandwidth per GPU (GB/s).
407
+ # https://github.com/NVIDIA/nccl/blob/master/src/graph/topo.h (link speed constants)
408
+ _GPU_NVLINK_BW: dict[NVIDIA_GPU_TYPE, float] = {
409
+ NVIDIA_GPU_TYPE.VOLTA: 120.0,
410
+ NVIDIA_GPU_TYPE.AMPERE: 240.0,
411
+ NVIDIA_GPU_TYPE.HOPPER: 370.0,
412
+ NVIDIA_GPU_TYPE.BLACKWELL: 720.0,
413
+ }
414
+
415
+ # PCIe effective intra-node bandwidth (GB/s) for NCCL ring.
416
+ # Conservative: GPU->CPU->GPU ring steps limit effective BW well below link rate.
417
+ _PCIE_INTRA_NODE_BW = 24.0
418
+
419
+ # Per-GPU inter-node bandwidth (GB/s), assuming 1:1 GPU:NIC ratio.
420
+ # HDR: 200Gbps=25GB/s, NDR: 400Gbps=50GB/s per NIC.
421
+ _GPU_INTER_NODE_BW: dict[NVIDIA_GPU_TYPE, float] = {
422
+ NVIDIA_GPU_TYPE.VOLTA: 12.0,
423
+ NVIDIA_GPU_TYPE.AMPERE: 25.0,
424
+ NVIDIA_GPU_TYPE.HOPPER: 50.0,
425
+ NVIDIA_GPU_TYPE.BLACKWELL: 50.0,
426
+ }
427
+
428
+
429
+ def get_intra_node_bw() -> float:
430
+ """Return intra-node bandwidth in GB/s. Config overrides auto-detection."""
431
+ override = torch._inductor.config.intra_node_bw
432
+ if override is not None:
433
+ return float(override)
434
+ if not _has_nvlink():
435
+ return _PCIE_INTRA_NODE_BW
436
+ return _GPU_NVLINK_BW.get(get_gpu_type(), 240.0)
437
+
438
+
439
+ def get_inter_node_bw() -> float:
440
+ """Return inter-node (IB/RoCE) bandwidth in GB/s. Config overrides auto-detection."""
441
+ override = torch._inductor.config.inter_node_bw
442
+ if override is not None:
443
+ return float(override)
444
+ return _GPU_INTER_NODE_BW.get(get_gpu_type(), 25.0)
445
+
446
+
447
+ def _log2i(n: int) -> int:
448
+ """Integer log2, matching NCCL's log2i (floor of log2)."""
449
+ if n <= 0:
450
+ return 0
451
+ r = 0
452
+ while n > 1:
453
+ n >>= 1
454
+ r += 1
455
+ return r
456
+
457
+
458
+ def estimate_nccl_collective_runtime_nccl_estimator(snode) -> float | None: # type: ignore[no-untyped-def]
459
+ kernel = snode.node
460
+ if kernel is None:
461
+ raise AssertionError("snode.node must not be None")
462
+ py_kernel_name = getattr(kernel, "python_kernel_name", "")
463
+ pg_name = kernel.constant_args[-1] # type: ignore[attr-defined]
464
+ from torch.distributed.distributed_c10d import _resolve_process_group
465
+
466
+ pg = _resolve_process_group(pg_name)
467
+ rank: int = torch.distributed.get_rank(pg)
468
+ # TODO(ivankobzarev): Figure out how we can use time estimations,
469
+ # without cuda allocations.
470
+ device = torch.device(f"cuda:{rank}")
471
+
472
+ fn = eval(py_kernel_name)
473
+ args, kwargs = snode_args_kwargs(snode)
474
+
475
+ # TODO(ivankobzarev): fix out variants snode_args_kwargs
476
+ if "all_gather_into_tensor_out" in py_kernel_name:
477
+ args = args[1:] + args[0]
478
+
479
+ with torch.distributed._time_estimator(group=pg, device=device) as time_estimator:
480
+ w = fn(*args, **kwargs)
481
+ torch.ops._c10d_functional.wait_tensor.default(w)
482
+
483
+ est_time_us = time_estimator.estimated_time
484
+ if est_time_us is None:
485
+ raise AssertionError("NCCL time estimator did not produce a result")
486
+ # -1000 constant is NCCL return in case of error during estimations.
487
+ # Observed it for all_to_all estimations.
488
+ if est_time_us < 0:
489
+ return None
490
+ est_time_ms = est_time_us / 1e3
491
+ return est_time_ms
492
+
493
+
494
+ def _nccl_algo_time(
495
+ nBytes: int,
496
+ group_size: int,
497
+ coll: NCCL_COLL,
498
+ algo: int,
499
+ proto: int,
500
+ ) -> float:
501
+ """Compute NCCL estimated time in us for a given (algo, proto) pair.
502
+
503
+ Mirrors ncclTopoTuneModel bandwidth/latency computation and
504
+ ncclTopoGetAlgoTime from NCCL tuning.cc. Returns -1 if the
505
+ (algo, proto) combination is disabled for this configuration.
506
+ """
507
+ gpus_per_node = torch.cuda.device_count() if torch.cuda.is_available() else 8
508
+ nNodes = math.ceil(group_size / gpus_per_node)
509
+ nRanks = group_size
510
+ compCapIndex = get_gpu_type()
511
+ index2 = nNodes - 1 if nNodes <= 2 else 2
512
+
513
+ # Total bus bandwidth (not per-channel). Auto-detected from GPU
514
+ # generation, or overridden by config. nChannels is only used for
515
+ # per-channel BW cap table lookups.
516
+ bwIntra = get_intra_node_bw()
517
+ bwInter = get_inter_node_bw()
518
+ nChannels = _GPU_NCHANNELS.get(compCapIndex, 8)
519
+
520
+ # Detect interconnect for IB-specific corrections
521
+ interconnect = detect_interconnect(group_size)
522
+ is_ib = interconnect in (InterconnectType.IB_NDR, InterconnectType.IB_HDR)
523
+
524
+ # LL128: disable for inter-node IB (BW tables calibrated for NVLink only)
525
+ # and for large-scale multi-node (>2 nodes)
526
+ if proto == NCCL_PROTO.LL128:
527
+ if nNodes > 2:
528
+ return -1.0
529
+ if nNodes > 1 and is_ib:
530
+ return -1.0
531
+
532
+ # --- Bandwidth computation (mirrors ncclTopoTuneModel) ---
533
+ # For IB interconnect, always use inter-node BW (bwIntra only for NVLink).
534
+ # Original NCCL tuning.cc uses bwIntra for nNodes<=2, designed for NVSwitch;
535
+ # doesn't apply to IB.
536
+ if nNodes == 1:
537
+ bw = bwIntra
538
+ elif is_ib:
539
+ bw = bwInter
540
+ else:
541
+ bw = bwIntra if nNodes <= 2 else bwInter
542
+
543
+ # IB corrections calibrated against H100 GrandTeton RoCE profiles
544
+ # (see agent_space/nccl_model_validation.md for calibration data):
545
+ if is_ib and nNodes > 1:
546
+ # NIC efficiency: fewer nodes → fewer NICs utilized → lower effective BW.
547
+ # 2-node (single inter-hop): ~0.80×; 8+ nodes: ~1.0×
548
+ nic_efficiency = 0.77 + 0.23 * min(1.0, (nNodes - 1) / 7)
549
+ bw *= nic_efficiency
550
+ # Multi-rail: larger messages utilize more NICs (8 NICs per H100 node).
551
+ # Power-law fit (exponent 0.17) to non-coalesced profile BW vs size.
552
+ if nNodes > 2:
553
+ multi_rail = (max(nBytes, 50_000_000) / 50_000_000) ** 0.17
554
+ bw *= multi_rail
555
+
556
+ busBw = bw
557
+
558
+ index1 = compCapIndex if nNodes == 1 else 0
559
+ llMaxBw = llMaxBws[index1][index2]
560
+
561
+ if algo == NCCL_ALGO.RING and proto == NCCL_PROTO.LL:
562
+ busBw = min(llMaxBw, busBw * 0.5)
563
+ elif algo == NCCL_ALGO.RING and proto == NCCL_PROTO.LL128:
564
+ busBw = min(
565
+ busBw * (120.0 / 128.0),
566
+ nChannels * perChMaxRingLL128Bws[compCapIndex][index2],
567
+ )
568
+ elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.LL:
569
+ busBw = min(busBw * (1.0 / 3.8), llMaxBw)
570
+ elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.LL128:
571
+ factor = 7.0 / 9.0 if nNodes == 1 else 120.0 / 128.0
572
+ busBw = min(
573
+ busBw * factor,
574
+ nChannels * perChMaxTreeLL128Bws[compCapIndex][index2],
575
+ )
576
+ elif algo == NCCL_ALGO.TREE and proto == NCCL_PROTO.SIMPLE:
577
+ if coll == NCCL_COLL.ALL_REDUCE:
578
+ busBw = min(busBw * 0.92, nChannels * perChMaxTreeBws[compCapIndex][index2])
579
+ # Ring+SIMPLE: no extra cap beyond busBw
580
+
581
+ if busBw <= 0:
582
+ return -1.0
583
+
584
+ # nsteps for the collective
585
+ if coll == NCCL_COLL.ALL_REDUCE:
586
+ nsteps = 2 * (nRanks - 1)
587
+ elif coll in (NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_GATHER):
588
+ nsteps = nRanks - 1
589
+ elif coll == NCCL_COLL.ALL_TO_ALL:
590
+ nsteps = 2 * (nRanks - 1)
591
+ elif coll == NCCL_COLL.P2P:
592
+ nsteps = 1
593
+ else:
594
+ return -1.0
595
+
596
+ # Bus BW to algorithm BW conversion
597
+ # Tree allreduce uses 0.5 ratio; Ring uses nRanks/nsteps
598
+ if algo == NCCL_ALGO.TREE and coll == NCCL_COLL.ALL_REDUCE:
599
+ bandwidth = busBw * 0.5
600
+ elif algo == NCCL_ALGO.RING:
601
+ bandwidth = busBw * (1.0 * nRanks / nsteps)
602
+ else:
603
+ bandwidth = busBw * 0.5
604
+
605
+ if bandwidth <= 0:
606
+ return -1.0
607
+
608
+ # --- Latency computation (mirrors ncclTopoTuneModel) ---
609
+ intraHw = NCCL_HW.PCI if interconnect == InterconnectType.PCIE else NCCL_HW.NVLINK
610
+ lat = baseLat[algo][proto]
611
+ intraLat = hwLat[intraHw][algo][proto]
612
+ interLat = hwLat[NCCL_HW.NET][algo][proto]
613
+
614
+ netOverhead = 1.0 if nNodes > 1 else 0.0
615
+ if proto == NCCL_PROTO.SIMPLE and nNodes > 1:
616
+ netOverhead *= 3.0
617
+ intraLat = max(intraLat, netOverhead)
618
+
619
+ if algo == NCCL_ALGO.RING:
620
+ nInterSteps = (
621
+ 0
622
+ if nNodes == 1
623
+ else (2 * (nNodes - 1) if coll == NCCL_COLL.ALL_REDUCE else nNodes - 1)
624
+ )
625
+ lat += (nsteps - nInterSteps) * intraLat + nInterSteps * interLat
626
+ elif algo == NCCL_ALGO.TREE:
627
+ if coll == NCCL_COLL.ALL_REDUCE:
628
+ lat += 2 * (
629
+ (nRanks // max(nNodes, 1) - 1) * intraLat + _log2i(nNodes) * interLat
630
+ )
631
+
632
+ # --- ncclTopoGetAlgoTime: time = lat + nBytes / (1000 * bandwidth) ---
633
+ # Tree correction factor for medium messages
634
+ if algo == NCCL_ALGO.TREE and coll == NCCL_COLL.ALL_REDUCE:
635
+ logSize = _log2i(nBytes >> 6) if nBytes >= 64 else 0
636
+ if 0 <= logSize < 24:
637
+ bandwidth *= treeCorrectionFactor[proto][logSize]
638
+
639
+ time_us = lat + nBytes / (1000.0 * bandwidth)
640
+ return time_us
641
+
642
+
643
+ def _nccl_best_algo_time(
644
+ nBytes: int,
645
+ group_size: int,
646
+ coll: NCCL_COLL,
647
+ ) -> tuple[float, int, int]:
648
+ """Find the best (algo, proto) for a given collective and return (time_us, algo, proto).
649
+
650
+ Iterates all supported (algo, proto) combinations and picks the one with
651
+ minimum estimated time, mirroring NCCL's algorithm selection.
652
+ """
653
+ best_time = float("inf")
654
+ best_algo = NCCL_ALGO.RING
655
+ best_proto = NCCL_PROTO.LL
656
+
657
+ for algo in (NCCL_ALGO.TREE, NCCL_ALGO.RING):
658
+ # Tree only supports allreduce in our model
659
+ if algo == NCCL_ALGO.TREE and coll != NCCL_COLL.ALL_REDUCE:
660
+ continue
661
+ for proto in (NCCL_PROTO.LL, NCCL_PROTO.LL128, NCCL_PROTO.SIMPLE):
662
+ t = _nccl_algo_time(nBytes, group_size, coll, algo, proto)
663
+ if 0 <= t < best_time:
664
+ best_time = t
665
+ best_algo = algo
666
+ best_proto = proto
667
+
668
+ return best_time, best_algo, best_proto
669
+
670
+
671
+ def estimate_nccl_collective_runtime_impl(
672
+ tensor_storage_size_bytes: int, group_size: int, coll: NCCL_COLL
673
+ ) -> float:
674
+ """Returns estimated NCCL collective runtime in milliseconds (ms).
675
+
676
+ Uses a multi-algorithm, multi-protocol model aligned with NCCL's
677
+ ncclTopoTuneModel and ncclTopoGetAlgoTime (tuning.cc). Evaluates
678
+ Ring and Tree algorithms across LL, LL128, and SIMPLE protocols,
679
+ selecting the (algo, proto) pair that minimizes estimated time.
680
+ """
681
+ if group_size <= 1:
682
+ return 0
683
+
684
+ if coll == NCCL_COLL.UNSUPPORTED:
685
+ return 0
686
+
687
+ time_us, _, _ = _nccl_best_algo_time(tensor_storage_size_bytes, group_size, coll)
688
+ if time_us < 0 or time_us == float("inf"):
689
+ return 0
690
+ return time_us / 1000.0
691
+
692
+
693
+ def compute_min_saturation_bytes(
694
+ group_size: int,
695
+ coll: NCCL_COLL,
696
+ target_efficiency: float = 0.9,
697
+ ) -> int:
698
+ """Compute min message size for target BW efficiency using empirical profiles.
699
+
700
+ Uses per-interconnect profiles calibrated to real NCCL behavior (algorithm,
701
+ protocol, channel selection) rather than the analytical model.
702
+ """
703
+ _SUPPORTED = (NCCL_COLL.ALL_GATHER, NCCL_COLL.REDUCE_SCATTER, NCCL_COLL.ALL_REDUCE)
704
+ if coll not in _SUPPORTED:
705
+ raise AssertionError(
706
+ f"Unsupported collective {coll}, expected one of {_SUPPORTED}"
707
+ )
708
+
709
+ if group_size <= 1:
710
+ return 0
711
+
712
+ profile = INTERCONNECT_PROFILES[detect_interconnect(group_size)]
713
+
714
+ if coll in (NCCL_COLL.ALL_GATHER, NCCL_COLL.REDUCE_SCATTER):
715
+ nsteps = group_size - 1
716
+ elif coll == NCCL_COLL.ALL_REDUCE:
717
+ nsteps = 2 * (group_size - 1)
718
+ else:
719
+ return 0
720
+
721
+ total_latency_us = profile.base_latency_us + nsteps * profile.latency_per_hop_us
722
+ latency_s = total_latency_us * 1e-6
723
+ bw_bytes_per_s = profile.bus_bw_GBps * 1e9
724
+ eff_ratio = target_efficiency / (1.0 - target_efficiency)
725
+ min_bytes = int(eff_ratio * latency_s * bw_bytes_per_s)
726
+ return max(min_bytes, profile.min_saturation_bytes)
727
+
728
+
729
+ ################################################################################################################
730
+ # The above code and constants are adapted from https://github.com/NVIDIA/nccl/blob/master/src/graph/tuning.cc #
731
+ ################################################################################################################
732
+
733
+
734
+ def estimate_nccl_collective_runtime(node: ir.IRNode) -> float:
735
+ """Returns estimated NCCL collective runtime in milliseconds (ms).
736
+
737
+ Uses the multi-algorithm, multi-protocol analytical model aligned with
738
+ NCCL's tuning.cc to select the best (algo, proto) pair for the given
739
+ collective size and topology.
740
+ """
741
+ tensor_storage_size_bytes = get_collective_input_size_bytes(node)
742
+ group_size = get_collective_group_size(node)
743
+ coll = get_collective_type(node)
744
+ return estimate_nccl_collective_runtime_impl(
745
+ tensor_storage_size_bytes, group_size, coll
746
+ )
747
+
748
+
749
+ def estimate_fx_collective_size(fx_node: torch.fx.Node) -> int:
750
+ """Estimate the size of a collective operation in bytes, including inputs and outputs."""
751
+ input_bytes = None
752
+
753
+ args, kwargs = fx_node.args, fx_node.kwargs
754
+ kwargs = dict(kwargs)
755
+
756
+ # don't double count pre-allocated buffer passed in
757
+ kwargs.pop("out", None)
758
+
759
+ def tensor_bytes(t: torch.Tensor) -> int:
760
+ return get_fx_node_size_numel(t.size()) * get_dtype_size(t.dtype)
761
+
762
+ def add_inp_bytes(inp: torch.fx.Node):
763
+ inp_val = inp.meta.get("val", None)
764
+ if not isinstance(inp_val, torch.Tensor):
765
+ return
766
+
767
+ nonlocal input_bytes
768
+ if input_bytes is None:
769
+ input_bytes = 0
770
+ input_bytes += tensor_bytes(inp_val)
771
+
772
+ pytree.tree_map_only(
773
+ torch.fx.Node,
774
+ add_inp_bytes,
775
+ (args, kwargs),
776
+ )
777
+
778
+ output_val = fx_node.meta.get("val", None)
779
+
780
+ if input_bytes is None or output_val is None:
781
+ return 0
782
+
783
+ # Coalesced collectives return a list of tensors
784
+ if isinstance(output_val, (list, tuple)):
785
+ output_bytes = sum(
786
+ tensor_bytes(t) for t in output_val if isinstance(t, torch.Tensor)
787
+ )
788
+ elif isinstance(output_val, torch.Tensor):
789
+ output_bytes = tensor_bytes(output_val)
790
+ else:
791
+ return 0
792
+
793
+ return input_bytes + output_bytes
794
+
795
+
796
+ def estimate_fx_collective_memory_footprint(fx_node: torch.fx.Node) -> int:
797
+ """Estimate the memory footprint of a collective operation in bytes.
798
+
799
+ This returns the total bytes that need to be live concurrently in memory.
800
+ For all_reduce, we divide by 2 since it can be done in-place.
801
+ """
802
+ from torch._inductor.fx_passes.bucketing import (
803
+ is_all_reduce_tensor as is_all_reduce,
804
+ )
805
+
806
+ size = estimate_fx_collective_size(fx_node)
807
+ return size if not is_all_reduce(fx_node) else size // 2
808
+
809
+
810
+ def estimate_nccl_collective_runtime_from_fx_node(
811
+ fx_node: torch.fx.Node,
812
+ override_size: int | None = None,
813
+ use_nccl_estimator: bool = True,
814
+ ) -> float:
815
+ """Returns estimated NCCL collective runtime in milliseconds (ms).
816
+
817
+ Tries the NCCL simulator first (if available and enabled), falls back
818
+ to the multi-algo/proto analytical model from tuning.cc.
819
+ """
820
+ from torch.distributed.distributed_c10d import _get_group_size_by_name
821
+
822
+ if fx_node.target is torch.ops._c10d_functional.all_to_all_single.default:
823
+ # TODO(ivankobzarev): Temporarily disabled - NCCL estimator returns internal error.
824
+ # for all_to_all during inductor compilation. Falls back to heuristic estimation.
825
+ use_nccl_estimator = False
826
+
827
+ if override_size is None:
828
+ tensor_storage_size_bytes = estimate_fx_collective_size(fx_node)
829
+ else:
830
+ tensor_storage_size_bytes = override_size
831
+
832
+ if isinstance(fx_node.target, str):
833
+ raise AssertionError(f"fx_node.target must not be a str, got {fx_node.target}")
834
+ opt_args_kwargs = normalize_function(
835
+ fx_node.target,
836
+ args=fx_node.args,
837
+ kwargs=fx_node.kwargs,
838
+ normalize_to_only_use_kwargs=True,
839
+ )
840
+ if opt_args_kwargs is None:
841
+ raise AssertionError("normalize_function returned None")
842
+ args, kwargs = opt_args_kwargs
843
+
844
+ from torch._inductor.fx_passes.bucketing import _resolve_group_name
845
+
846
+ group_name = _resolve_group_name(kwargs["group_name"])
847
+ group_size = _get_group_size_by_name(group_name)
848
+ if not isinstance(fx_node.target, torch._ops.OpOverload):
849
+ raise AssertionError(
850
+ f"expected fx_node.target to be an OpOverload, got {type(fx_node.target)}"
851
+ )
852
+ coll = get_collective_type_from_kernel_name(fx_node.target.name())
853
+
854
+ def _nccl_estimate() -> float | None:
855
+ # TODO: Refactor with estimate_nccl_collective_runtime_nccl_estimator
856
+ from torch.distributed.distributed_c10d import _resolve_process_group, Backend
857
+
858
+ pg = _resolve_process_group(group_name)
859
+ if torch.distributed.distributed_c10d.get_backend(pg) == Backend.FAKE:
860
+ # nccl estimator requires real process group
861
+ return None
862
+
863
+ device = torch.device("cuda")
864
+ try:
865
+ backend = pg._get_backend(device)
866
+ except RuntimeError:
867
+ return None
868
+ if not backend.supports_time_estimate:
869
+ return None
870
+
871
+ flat_args, flat_args_pytree_spec = pytree.tree_flatten((args, kwargs))
872
+
873
+ def _tensor(size, dtype, device) -> torch.Tensor: # type: ignore[no-untyped-def]
874
+ return torch.empty(
875
+ size if override_size is None else [override_size],
876
+ dtype=dtype,
877
+ device=device,
878
+ )
879
+
880
+ def to_real_tensor(e: Any) -> Any:
881
+ if isinstance(e, torch.fx.Node):
882
+ return to_real_tensor(e.meta["val"])
883
+ if isinstance(e, torch.Tensor):
884
+ return _tensor([get_fx_node_size_numel(e.size())], e.dtype, e.device)
885
+ return e
886
+
887
+ flat_args = [to_real_tensor(a) for a in flat_args]
888
+ real_args, real_kwargs = pytree.tree_unflatten(flat_args, flat_args_pytree_spec)
889
+
890
+ fn = fx_node.target
891
+ if not isinstance(fn, torch._ops.OpOverload):
892
+ raise AssertionError(
893
+ f"expected fx_node.target to be an OpOverload, got {type(fn)}"
894
+ )
895
+ with torch.distributed._time_estimator(
896
+ group=pg, device=device
897
+ ) as time_estimator:
898
+ w = fn(*real_args, **real_kwargs)
899
+ # Coalesced collectives return a list of tensors
900
+ if isinstance(w, (list, tuple)):
901
+ for t in w:
902
+ torch.ops._c10d_functional.wait_tensor.default(t)
903
+ else:
904
+ torch.ops._c10d_functional.wait_tensor.default(w)
905
+ est_time_us = time_estimator.estimated_time
906
+ if est_time_us is None:
907
+ raise AssertionError("NCCL time estimator did not produce a result")
908
+ # -1000 constant is NCCL return in case of error during estimations.
909
+ # Observed it for all_to_all estimations.
910
+ if est_time_us < 0:
911
+ return None
912
+ est_time_ms = est_time_us / 1e3
913
+ return est_time_ms
914
+
915
+ if use_nccl_estimator:
916
+ est_time_ms = _nccl_estimate()
917
+ if est_time_ms is not None:
918
+ return est_time_ms
919
+
920
+ return estimate_nccl_collective_runtime_impl(
921
+ tensor_storage_size_bytes, group_size, coll
922
+ )
.venv/lib/python3.12/site-packages/torch/_inductor/comm_lowering.py ADDED
@@ -0,0 +1,967 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ import logging
3
+
4
+ import torch
5
+ import torch.utils._pytree as pytree
6
+ from torch._inductor.utils import is_symbolic
7
+ from torch.utils._ordered_set import OrderedSet
8
+
9
+ from . import config, ir
10
+ from .virtualized import V
11
+
12
+
13
+ log = logging.getLogger(__name__)
14
+
15
+
16
+ # NOTE [lowering-time collective optimization]
17
+ #
18
+ # In collective communication libraries such as NCCL, every rank maintains
19
+ # communication buffers that are remotely accessible by some peers. Depending
20
+ # on the underlying transport, remote accessibility may be established via
21
+ # mechanisms such as ib_reg_mr, CUDA P2P, or CUDA multicast. Typically, these
22
+ # buffers are private to the communication library by default, and
23
+ # communication ops copy user data in and out of these buffers.
24
+ #
25
+ # To prevent these copies, an optimization commonly known as "user buffer
26
+ # registration" can be employed. This allows direct establishment of remote
27
+ # accessibility on user buffers, eliminating the need for copying. However,
28
+ # this optimization introduces stringent usage requirements, which are
29
+ # typically hard to satisfy without being intrusive to the user code:
30
+ #
31
+ # - Establishing remote accessibility is expensive and often done ahead of
32
+ # time. In such implementations, all ranks must agree on the set of allocations
33
+ # used for every collective op. Failing to meet this requirement can
34
+ # lead to runtime errors or even silent correctness issues.
35
+ # - Even if the collective communication library supports gracefully falling
36
+ # back to "unregistered" implementations, the fallback mechanism would nullify
37
+ # the optimization.
38
+ # - Some communication mechanisms impose stricter requirements than others. For
39
+ # example, CUDA's multicast + multi-mem instructions require all ranks to agree
40
+ # not only on the allocations used for every collective but also on the offsets
41
+ # within these allocations.
42
+ #
43
+ # To support all different mechanisms with optimal results, we aim to satisfy
44
+ # the strictest requirement for this family of optimizations - we ensure that
45
+ # every collective op invocation is guaranteed to operate on the same
46
+ # allocation, at the same offset, in every iteration.
47
+ #
48
+ # For eligible collective ops, we identify communication buffers at lowering
49
+ # time and optionally choose to lower the op to a different kernel
50
+ # (communication libraries like NCCL handle both registered and non-registered
51
+ # buffers transparently within the same op, though some may require different
52
+ # ops for different cases). Later, the codegen will perform "persistent
53
+ # allocation" to satisfy the aforementioned constraints, and optionally,
54
+ # perform buffer planning to optimize overall memory usage.
55
+ def can_realize_as_comm_buffer(
56
+ x: ir.TensorBox, comm_buffer_type: ir.CommBufferType
57
+ ) -> bool:
58
+ """
59
+ Check if an input can be realized as a comm buffer of the specified
60
+ `comm_buffer_type`.
61
+ """
62
+ data = _get_data(x)
63
+
64
+ if isinstance(data, ir.Loops):
65
+ return True
66
+
67
+ # We cannot realize buffers as comm buffers if we don't control their
68
+ # allocation.
69
+ if isinstance(data, ir.Buffer) and not data.should_allocate():
70
+ return False
71
+
72
+ layout = data.get_output_spec()
73
+ if isinstance(layout, ir.CommBufferLayout):
74
+ return True
75
+
76
+ if isinstance(layout, ir.FixedLayout):
77
+ return True
78
+
79
+ if isinstance(layout, ir.FlexibleLayout) and not is_symbolic(data.get_numel()):
80
+ return True
81
+
82
+ return False
83
+
84
+
85
+ def realize_as_comm_buffer(
86
+ x: ir.TensorBox,
87
+ comm_buffer_type: ir.CommBufferType,
88
+ group_name: "torch.distributed.distributed_c10d.GroupName",
89
+ ) -> None:
90
+ """
91
+ Realize an input as a comm buffer of the specified `comm_buffer_type`.
92
+
93
+ Specifically, this realizes the underlying buffer if it's still unrealized
94
+ and changes the layout of the buffer to `ir.CommBufferLayout`.
95
+ """
96
+ x.realize()
97
+ buffer = _get_data(x)
98
+ if not isinstance(buffer, ir.Buffer):
99
+ raise AssertionError(f"expected an `ir.Buffer`, got {type(buffer)}")
100
+
101
+ layout = buffer.get_output_spec()
102
+ if isinstance(layout, ir.CommBufferLayout):
103
+ return
104
+
105
+ # The buffer may have already been frozen to FixedLayout if it was used
106
+ # by another operation before the comm operation.
107
+ if not isinstance(layout, (ir.FlexibleLayout, ir.FixedLayout)):
108
+ raise AssertionError(
109
+ "A buffer can only be realized as a comm buffer if it "
110
+ f"has `FlexibleLayout` or `FixedLayout` (got {layout})."
111
+ )
112
+
113
+ if is_symbolic(buffer.get_numel()):
114
+ raise AssertionError(
115
+ "A buffer with symbolic shape cannot be converted to "
116
+ f"a comm buffer (got {layout})."
117
+ )
118
+
119
+ buffer.layout = ir.CommBufferLayout(
120
+ layout=layout,
121
+ comm_buffer_type=comm_buffer_type,
122
+ group_name=group_name,
123
+ )
124
+
125
+
126
+ def _get_data(x: ir.TensorBox) -> ir.IRNode:
127
+ if isinstance(x.data, ir.BaseView):
128
+ # TensorBox -> *View -> StorageBox -> IRNode
129
+ node = x.data.unwrap_view()
130
+ if not isinstance(node, (ir.BaseView, ir.MutableBox)):
131
+ raise AssertionError(
132
+ f"expected an `ir.BaseView` or `ir.MutableBox`, got {type(node)}"
133
+ )
134
+ return node.data
135
+ elif isinstance(x.data, ir.StorageBox):
136
+ # TensorBox -> StorageBox -> IRNode
137
+ return x.data.data
138
+ else:
139
+ raise AssertionError(
140
+ "Expect the data attr of a `TensorBox` to be either "
141
+ f"an `ir.BaseView` or `ir.StorageBox` (got {x.data})."
142
+ )
143
+
144
+
145
+ _bufs_to_skip_wait = OrderedSet[tuple[int, str]]()
146
+
147
+
148
+ def mark_as_skip_wait(x: ir.IRNode) -> None:
149
+ """
150
+ If a non-blocking collective is lowered as a blocking collective, the wait
151
+ node in the original graph becomes useless and we can skip the lowering it.
152
+ """
153
+ _bufs_to_skip_wait.add((id(V.graph), x.get_name()))
154
+
155
+
156
+ def should_skip_wait(x: ir.IRNode) -> bool:
157
+ return (id(V.graph), x.get_name()) in _bufs_to_skip_wait
158
+
159
+
160
+ def _should_lower_as_one_shot_all_reduce(
161
+ inp: ir.TensorBox,
162
+ reduce_op: str,
163
+ group_name: "torch.distributed.distributed_c10d.GroupName",
164
+ ):
165
+ from torch.distributed._symmetric_memory import is_symm_mem_enabled_for_group
166
+
167
+ inp_size = inp.get_numel() * inp.get_dtype().itemsize
168
+ return (
169
+ config._collective.auto_select
170
+ and is_symm_mem_enabled_for_group(group_name)
171
+ and can_realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM)
172
+ and reduce_op == "sum"
173
+ and inp_size <= config._collective.one_shot_all_reduce_threshold_bytes
174
+ )
175
+
176
+
177
+ def _one_shot_all_reduce(inp: ir.TensorBox, reduce_op, group_name):
178
+ realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM, group_name)
179
+ return pytree.tree_map(
180
+ ir.TensorBox.create,
181
+ ir.FallbackKernel.create(
182
+ torch.ops.symm_mem.one_shot_all_reduce.default,
183
+ inp,
184
+ reduce_op,
185
+ group_name,
186
+ ),
187
+ )
188
+
189
+
190
+ def _create_out_of_place(kernel, inputs, *args) -> ir.IRNode:
191
+ node = ir._CollectiveKernel.create_out_of_place(kernel, inputs, *args)
192
+ if not isinstance(node, ir.IRNode):
193
+ raise AssertionError(f"expected an `ir.IRNode`, got {type(node)}")
194
+ return ir.TensorBox.create(node)
195
+
196
+
197
+ def register_comm_lowerings():
198
+ """
199
+ Register lowerings for the comm subsystem.
200
+ """
201
+ try:
202
+ _ = torch.ops._c10d_functional.all_reduce
203
+ except AttributeError:
204
+ log.info(
205
+ "Inductor support for distributed collectives depends on building "
206
+ "torch.distributed"
207
+ )
208
+ return
209
+
210
+ from .lowering import (
211
+ add_layout_constraint,
212
+ clone,
213
+ constrain_to_fx_strides,
214
+ copy_,
215
+ register_lowering,
216
+ )
217
+
218
+ def register_comm_lowering(fn):
219
+ add_layout_constraint(fn, constrain_to_fx_strides)
220
+ return register_lowering(fn)
221
+
222
+ c10d = torch.ops._c10d_functional
223
+
224
+ @register_comm_lowering(c10d.all_reduce) # type: ignore[misc]
225
+ def _all_reduce(
226
+ inp: ir.TensorBox,
227
+ reduce_op: str,
228
+ group_name: "torch.distributed.distributed_c10d.GroupName",
229
+ ) -> ir.TensorBox:
230
+ if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name):
231
+ return _one_shot_all_reduce(inp, reduce_op, group_name)
232
+
233
+ # Lower as c10d.all_reduce_
234
+ inp = clone(inp)
235
+ if config.reorder_for_compute_comm_overlap:
236
+ # The horizontal fusion of this clone often severely delays the
237
+ # scheduling of the all_reduce_ node. Horizontally fusing this
238
+ # clone can almost never out-perform scheduling the all_reduce_
239
+ # earlier. Also in most cases, this clone is eliminated via
240
+ # in-place reuse. Therefore, we tell the scheduler to not fuse it.
241
+ inp.realize()
242
+ V.graph.no_fuse_buffer_names.add(inp.get_name())
243
+ # pyrefly: ignore [bad-assignment]
244
+ inp = ir.ExternKernel.require_contiguous(inp)
245
+ # Because we are lowering as inplace c10d.all_reduce_, we should generate
246
+ # _AllReduce_Kernel instead of _AllReduceKernel.
247
+ ir._AllReduce_Kernel.create_inplace(
248
+ c10d.all_reduce_.default,
249
+ inp, # type: ignore[arg-type]
250
+ reduce_op,
251
+ group_name, # type: ignore[arg-type]
252
+ )
253
+ return inp # type: ignore[return-value]
254
+
255
+ @register_comm_lowering(c10d.all_reduce_) # type: ignore[misc]
256
+ def _all_reduce_(
257
+ inp: ir.TensorBox,
258
+ reduce_op: str,
259
+ group_name: "torch.distributed.distributed_c10d.GroupName",
260
+ ) -> ir.TensorBox:
261
+ if _should_lower_as_one_shot_all_reduce(inp, reduce_op, group_name):
262
+ ret = copy_(
263
+ inp,
264
+ _one_shot_all_reduce(inp, reduce_op, group_name),
265
+ )
266
+ mark_as_skip_wait(ret)
267
+ return inp
268
+
269
+ # Lower as c10d.all_reduce_
270
+ # pyrefly: ignore [bad-assignment]
271
+ inp = ir.ExternKernel.require_contiguous(inp)
272
+ ir._AllReduce_Kernel.create_inplace(
273
+ c10d.all_reduce_.default,
274
+ inp, # type: ignore[arg-type]
275
+ reduce_op,
276
+ group_name, # type: ignore[arg-type]
277
+ )
278
+ return inp # type: ignore[return-value]
279
+
280
+ @register_comm_lowering(c10d.all_reduce_coalesced)
281
+ def _all_reduce_coalesced(inputs, reduce_op, group_name):
282
+ inputs = [clone(inp) for inp in inputs]
283
+ ir._CollectiveKernel.create_inplace(
284
+ c10d.all_reduce_coalesced_.default,
285
+ inputs,
286
+ reduce_op,
287
+ group_name,
288
+ )
289
+ return inputs
290
+
291
+ @register_comm_lowering(c10d.all_reduce_coalesced_)
292
+ def _all_reduce_coalesced_(inputs, reduce_op, group_name):
293
+ ir._CollectiveKernel.create_inplace(
294
+ c10d.all_reduce_coalesced_.default,
295
+ inputs,
296
+ reduce_op,
297
+ group_name,
298
+ )
299
+ return inputs
300
+
301
+ @register_comm_lowering(c10d.all_gather_into_tensor)
302
+ def _all_gather_into_tensor(inp, group_size, group_name):
303
+ return _create_out_of_place(
304
+ c10d.all_gather_into_tensor.default,
305
+ inp,
306
+ group_size,
307
+ group_name,
308
+ )
309
+
310
+ @register_comm_lowering(c10d.all_gather_into_tensor_coalesced)
311
+ def _all_gather_into_tensor_coalesced(inputs, group_size, group_name):
312
+ return pytree.tree_map(
313
+ ir.TensorBox.create,
314
+ ir._CollectiveKernel.create_out_of_place(
315
+ c10d.all_gather_into_tensor_coalesced.default,
316
+ inputs,
317
+ group_size,
318
+ group_name,
319
+ ),
320
+ )
321
+
322
+ @register_comm_lowering(c10d.all_gather_into_tensor_out)
323
+ def _all_gather_into_tensor_out(inp, group_size, group_name, *, out):
324
+ ir._CollectiveKernel.create_inplace(
325
+ c10d.all_gather_into_tensor_out.default,
326
+ inp,
327
+ group_size,
328
+ group_name,
329
+ out=out,
330
+ )
331
+ return out
332
+
333
+ @register_comm_lowering(c10d.reduce_scatter_tensor)
334
+ def _reduce_scatter_tensor(inp, reduce_op, group_size, group_name):
335
+ return _create_out_of_place(
336
+ c10d.reduce_scatter_tensor.default,
337
+ inp,
338
+ reduce_op,
339
+ group_size,
340
+ group_name,
341
+ )
342
+
343
+ @register_comm_lowering(c10d.reduce_scatter_tensor_out)
344
+ def _reduce_scatter_tensor_out(inp, reduce_op, group_size, group_name, *, out):
345
+ ir._CollectiveKernel.create_inplace(
346
+ c10d.reduce_scatter_tensor_out.default,
347
+ inp,
348
+ reduce_op,
349
+ group_size,
350
+ group_name,
351
+ out=out,
352
+ )
353
+ return out
354
+
355
+ @register_comm_lowering(c10d.reduce_scatter_tensor_coalesced)
356
+ def _reduce_scatter_tensor_coalesced(inputs, reduce_op, group_size, group_name):
357
+ return pytree.tree_map(
358
+ ir.TensorBox.create,
359
+ ir._CollectiveKernel.create_out_of_place(
360
+ c10d.reduce_scatter_tensor_coalesced.default,
361
+ inputs,
362
+ reduce_op,
363
+ group_size,
364
+ group_name,
365
+ ),
366
+ )
367
+
368
+ @register_comm_lowering(c10d.all_to_all_single)
369
+ def _all_to_all_single(inp, output_split_sizes, input_split_sizes, group_name):
370
+ return _create_out_of_place(
371
+ c10d.all_to_all_single.default,
372
+ inp,
373
+ output_split_sizes,
374
+ input_split_sizes,
375
+ group_name,
376
+ )
377
+
378
+ @register_comm_lowering(c10d.broadcast)
379
+ def _broadcast(inp, src, group_name):
380
+ inp = clone(inp)
381
+ ir._CollectiveKernel.create_inplace(
382
+ c10d.broadcast_.default, inp, src, group_name
383
+ )
384
+ return inp
385
+
386
+ @register_comm_lowering(c10d.broadcast_)
387
+ def _broadcast_(inp, src, group_name):
388
+ ir._CollectiveKernel.create_inplace(
389
+ c10d.broadcast_.default, inp, src, group_name
390
+ )
391
+ return inp
392
+
393
+ @register_comm_lowering(torch.ops._dtensor.shard_dim_alltoall)
394
+ def _shard_dim_alltoall(inp, gather_dim, shard_dim, group_name):
395
+ return _create_out_of_place(
396
+ torch.ops._dtensor.shard_dim_alltoall.default,
397
+ inp,
398
+ gather_dim,
399
+ shard_dim,
400
+ group_name,
401
+ )
402
+
403
+ @register_comm_lowering(c10d.wait_tensor)
404
+ def _wait_tensor(inp):
405
+ if should_skip_wait(inp):
406
+ return inp
407
+
408
+ ir._WaitKernel.create_wait(c10d.wait_tensor.default, inp)
409
+ return inp
410
+
411
+ @register_comm_lowering(c10d.isend) # type: ignore[misc]
412
+ def _isend(inp, dst, tag, group_name):
413
+ inp = ir.ExternKernel.require_contiguous(inp)
414
+ return _create_out_of_place(c10d.isend.default, inp, dst, tag, group_name)
415
+
416
+ @register_comm_lowering(c10d.irecv) # type: ignore[misc]
417
+ def _irecv(inp, src, tag, group_name):
418
+ inp = ir.ExternKernel.require_contiguous(inp)
419
+ ir._CollectiveKernel.create_inplace(
420
+ c10d.irecv.default, inp, src, tag, group_name
421
+ )
422
+ return inp
423
+
424
+ @register_comm_lowering(c10d.batch_p2p_ops) # type: ignore[misc]
425
+ def _batch_p2p_ops(op_list, peer_list, tag_list, tensors, group_name):
426
+ tensors = [ir.ExternKernel.require_contiguous(t) for t in tensors]
427
+ kernel = c10d.batch_p2p_ops.default
428
+ with V.graph.fake_mode:
429
+ result = ir._CollectiveKernel.process_kernel(
430
+ kernel,
431
+ op_list,
432
+ peer_list,
433
+ tag_list,
434
+ tensors,
435
+ group_name,
436
+ )
437
+ example_output = result.example_output
438
+ tensor_args = result.tensor_args
439
+ non_tensor_args = result.non_tensor_args
440
+ unflatten_args = result.unflatten_args
441
+ if result.unbacked_bindings:
442
+ raise AssertionError(f"{kernel} {result.unbacked_bindings}")
443
+ for op, tensor_arg in zip(op_list, tensor_args):
444
+ tensor_arg.realize()
445
+ if op == "irecv":
446
+ V.graph.mark_buffer_mutated(tensor_arg.get_name())
447
+
448
+ device = tensor_args[0].get_device_or_error()
449
+ packed = ir._CollectiveKernel(
450
+ ir.MultiOutputLayout(device=device),
451
+ kernel,
452
+ tensor_args,
453
+ non_tensor_args,
454
+ unflatten_args,
455
+ )
456
+
457
+ results = []
458
+ for i, (op, t, ex_out) in enumerate(zip(op_list, tensors, example_output)):
459
+ if op == "irecv":
460
+ packed.mutation_outputs.append(
461
+ ir.MutationOutput(ir.NoneLayout(device=device), t, packed)
462
+ )
463
+ packed.alias_names.append(t.get_name())
464
+ results.append(t)
465
+ else:
466
+ # isend: 0-element placeholder output connected to the collective
467
+ placeholder = ir.MultiOutput(
468
+ ir._CollectiveKernel.tensor_to_layout(ex_out),
469
+ packed,
470
+ [(list, i)],
471
+ )
472
+ results.append(ir.TensorBox.create(placeholder))
473
+ return results
474
+
475
+
476
+ def register_symm_mem_lowerings():
477
+ """
478
+ Register lowerings for symmetric memory (symm_mem) operations.
479
+ """
480
+ try:
481
+ symm_mem = torch.ops.symm_mem
482
+ # Check for an actual operation, not just the namespace.
483
+ # torch.ops.symm_mem is a lazy namespace that always exists,
484
+ # but the operations may not exist on non-CUDA platforms or
485
+ # when USE_DISTRIBUTED is disabled.
486
+ _ = symm_mem.one_shot_all_reduce
487
+ except AttributeError:
488
+ log.info("symm_mem ops not available, skipping symm_mem lowerings")
489
+ return
490
+
491
+ from torch._library._out_variant import register_out_variant
492
+
493
+ # Register manual out variant mappings for symm_mem ops.
494
+ register_out_variant(
495
+ symm_mem.one_shot_all_reduce.default,
496
+ symm_mem.one_shot_all_reduce_out.default,
497
+ )
498
+ register_out_variant(
499
+ symm_mem.one_shot_all_reduce_copy.default,
500
+ symm_mem.one_shot_all_reduce_copy_out.default,
501
+ )
502
+
503
+ from .lowering import register_lowering
504
+
505
+ def _copy_input_to_comm_buffer(
506
+ inp: ir.TensorBox,
507
+ comm_buffer_type: ir.CommBufferType,
508
+ group_name: "torch.distributed.distributed_c10d.GroupName",
509
+ ) -> ir.TensorBox:
510
+ """
511
+ Fallback: insert a Pointwise identity copy allocated in P2P via
512
+ CommBufferLayout. Used when we don't control the input's allocation.
513
+ """
514
+ inp.realize()
515
+ copy = ir.Pointwise.create(
516
+ device=inp.get_device(),
517
+ dtype=inp.get_dtype(),
518
+ inner_fn=inp.make_loader(),
519
+ ranges=inp.get_size(),
520
+ )
521
+ realize_as_comm_buffer(copy, comm_buffer_type, group_name)
522
+ return copy
523
+
524
+ def _maybe_realize_symm_mem(
525
+ inp: ir.TensorBox,
526
+ group_name: str, # type: ignore[arg-type]
527
+ ) -> ir.TensorBox:
528
+ """
529
+ Ensure inp is in P2P memory for a symm_mem collective.
530
+
531
+ If inductor controls the buffer's allocation (ComputedBuffer,
532
+ or any buffer with FlexibleLayout/FixedLayout), switch its
533
+ layout to CommBufferLayout in-place, zero-copy.
534
+
535
+ If inductor does not control allocation (e.g. InputBuffer),
536
+ insert a Pointwise identity copy into a new CommBufferLayout buffer.
537
+ This adds an extra Triton kernel. Returns the possibly new TensorBox.
538
+
539
+ TODO(tianrengao): eliminate the extra kernel for static-shape
540
+ InputBuffers by pre-allocating P2P memory in the wrapper and DMA .copy_()
541
+ """
542
+ if can_realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM):
543
+ realize_as_comm_buffer(inp, ir.CommBufferType.SYMM_MEM, group_name) # type: ignore[arg-type]
544
+ return inp
545
+ else:
546
+ return _copy_input_to_comm_buffer(
547
+ inp,
548
+ ir.CommBufferType.SYMM_MEM,
549
+ group_name, # type: ignore[arg-type]
550
+ )
551
+
552
+ def _create_low_contention_ag_out(
553
+ kernel: torch._ops.OpOverload,
554
+ inp: ir.TensorBox,
555
+ group_name: "torch.distributed.distributed_c10d.GroupName",
556
+ ) -> ir.TensorBox:
557
+ from torch.distributed import distributed_c10d as c10d
558
+
559
+ inp.realize()
560
+ group_size = c10d._get_group_size_by_name(group_name)
561
+ out_size = [inp.get_size()[0] * group_size, *inp.get_size()[1:]]
562
+ layout = ir.CommBufferLayout(
563
+ ir.FixedLayout(
564
+ device=inp.get_device_or_error(),
565
+ dtype=inp.get_dtype(),
566
+ size=out_size,
567
+ ),
568
+ ir.CommBufferType.SYMM_MEM,
569
+ group_name,
570
+ )
571
+ return ir.TensorBox.create(
572
+ ir.ExternKernelOut(
573
+ layout=layout,
574
+ inputs=[inp],
575
+ constant_args=(group_name,),
576
+ op_overload=kernel,
577
+ )
578
+ )
579
+
580
+ @register_lowering(symm_mem.one_shot_all_reduce)
581
+ def _symm_mem_one_shot_all_reduce(
582
+ inp: ir.TensorBox,
583
+ reduce_op: str,
584
+ group_name: str,
585
+ ):
586
+ inp = _maybe_realize_symm_mem(inp, group_name)
587
+ return pytree.tree_map(
588
+ ir.TensorBox.create,
589
+ ir.FallbackKernel.create(
590
+ symm_mem.one_shot_all_reduce.default,
591
+ inp,
592
+ reduce_op,
593
+ group_name,
594
+ ),
595
+ )
596
+
597
+ @register_lowering(symm_mem.one_shot_all_reduce_out)
598
+ def _symm_mem_one_shot_all_reduce_out(
599
+ inp: ir.TensorBox,
600
+ reduce_op: str,
601
+ group_name: str,
602
+ out: ir.TensorBox,
603
+ ):
604
+ inp = _maybe_realize_symm_mem(inp, group_name)
605
+ return pytree.tree_map(
606
+ ir.TensorBox.create,
607
+ ir.FallbackKernel.create(
608
+ symm_mem.one_shot_all_reduce_out.default,
609
+ inp,
610
+ reduce_op,
611
+ group_name,
612
+ out,
613
+ ),
614
+ )
615
+
616
+ @register_lowering(symm_mem.one_shot_all_reduce_copy)
617
+ def _symm_mem_one_shot_all_reduce_copy(
618
+ symm_buffer: ir.TensorBox,
619
+ local_input: ir.TensorBox,
620
+ reduce_op: str,
621
+ group_name: str,
622
+ ):
623
+ symm_buffer = _maybe_realize_symm_mem(symm_buffer, group_name)
624
+ return pytree.tree_map(
625
+ ir.TensorBox.create,
626
+ ir.FallbackKernel.create(
627
+ symm_mem.one_shot_all_reduce_copy.default,
628
+ symm_buffer,
629
+ local_input,
630
+ reduce_op,
631
+ group_name,
632
+ ),
633
+ )
634
+
635
+ @register_lowering(symm_mem.one_shot_all_reduce_copy_out)
636
+ def _symm_mem_one_shot_all_reduce_copy_out(
637
+ symm_buffer: ir.TensorBox,
638
+ local_input: ir.TensorBox,
639
+ reduce_op: str,
640
+ group_name: str,
641
+ out: ir.TensorBox,
642
+ ):
643
+ symm_buffer = _maybe_realize_symm_mem(symm_buffer, group_name)
644
+ return pytree.tree_map(
645
+ ir.TensorBox.create,
646
+ ir.FallbackKernel.create(
647
+ symm_mem.one_shot_all_reduce_copy_out.default,
648
+ symm_buffer,
649
+ local_input,
650
+ reduce_op,
651
+ group_name,
652
+ out,
653
+ ),
654
+ )
655
+
656
+ @register_lowering(symm_mem.two_shot_all_reduce_)
657
+ def _symm_mem_two_shot_all_reduce_(
658
+ inp: ir.TensorBox,
659
+ reduce_op: str,
660
+ group_name: str,
661
+ ):
662
+ inp = _maybe_realize_symm_mem(inp, group_name)
663
+ ir.FallbackKernel.create(
664
+ symm_mem.two_shot_all_reduce_.default,
665
+ inp,
666
+ reduce_op,
667
+ group_name,
668
+ )
669
+ return inp
670
+
671
+ @register_lowering(symm_mem.two_shot_all_reduce_out)
672
+ def _symm_mem_two_shot_all_reduce_out(
673
+ inp: ir.TensorBox,
674
+ reduce_op: str,
675
+ group_name: str,
676
+ output: ir.TensorBox,
677
+ ):
678
+ inp = _maybe_realize_symm_mem(inp, group_name)
679
+ return pytree.tree_map(
680
+ ir.TensorBox.create,
681
+ ir.FallbackKernel.create(
682
+ symm_mem.two_shot_all_reduce_out.default,
683
+ inp,
684
+ reduce_op,
685
+ group_name,
686
+ output,
687
+ ),
688
+ )
689
+
690
+ @register_lowering(symm_mem.multimem_all_reduce_)
691
+ def _symm_mem_multimem_all_reduce_(
692
+ inp: ir.TensorBox,
693
+ reduce_op: str,
694
+ group_name: str,
695
+ ):
696
+ inp = _maybe_realize_symm_mem(inp, group_name)
697
+ ir.FallbackKernel.create(
698
+ symm_mem.multimem_all_reduce_.default,
699
+ inp,
700
+ reduce_op,
701
+ group_name,
702
+ )
703
+ return inp
704
+
705
+ @register_lowering(symm_mem.multimem_one_shot_all_reduce)
706
+ def _symm_mem_multimem_one_shot_all_reduce(
707
+ inp: ir.TensorBox,
708
+ reduce_op: str,
709
+ group_name: str,
710
+ ):
711
+ inp = _maybe_realize_symm_mem(inp, group_name)
712
+ return pytree.tree_map(
713
+ ir.TensorBox.create,
714
+ ir.FallbackKernel.create(
715
+ symm_mem.multimem_one_shot_all_reduce.default,
716
+ inp,
717
+ reduce_op,
718
+ group_name,
719
+ ),
720
+ )
721
+
722
+ @register_lowering(symm_mem.multimem_one_shot_all_reduce_out)
723
+ def _symm_mem_multimem_one_shot_all_reduce_out(
724
+ inp: ir.TensorBox,
725
+ reduce_op: str,
726
+ group_name: str,
727
+ out: ir.TensorBox,
728
+ ):
729
+ inp = _maybe_realize_symm_mem(inp, group_name)
730
+ return pytree.tree_map(
731
+ ir.TensorBox.create,
732
+ ir.FallbackKernel.create(
733
+ symm_mem.multimem_one_shot_all_reduce_out.default,
734
+ inp,
735
+ reduce_op,
736
+ group_name,
737
+ out,
738
+ ),
739
+ )
740
+
741
+ @register_lowering(symm_mem.multimem_one_shot_reduce_out)
742
+ def _symm_mem_multimem_one_shot_reduce_out(
743
+ inp: ir.TensorBox,
744
+ reduce_op: str,
745
+ root: int,
746
+ group_name: str,
747
+ out: ir.TensorBox,
748
+ ):
749
+ inp = _maybe_realize_symm_mem(inp, group_name)
750
+ return pytree.tree_map(
751
+ ir.TensorBox.create,
752
+ ir.FallbackKernel.create(
753
+ symm_mem.multimem_one_shot_reduce_out.default,
754
+ inp,
755
+ reduce_op,
756
+ root,
757
+ group_name,
758
+ out,
759
+ ),
760
+ )
761
+
762
+ @register_lowering(symm_mem.multimem_all_gather_out)
763
+ def _symm_mem_multimem_all_gather_out(
764
+ inp: ir.TensorBox,
765
+ group_name: str,
766
+ out: ir.TensorBox,
767
+ ):
768
+ inp = _maybe_realize_symm_mem(inp, group_name)
769
+ return pytree.tree_map(
770
+ ir.TensorBox.create,
771
+ ir.FallbackKernel.create(
772
+ symm_mem.multimem_all_gather_out.default,
773
+ inp,
774
+ group_name,
775
+ out,
776
+ ),
777
+ )
778
+
779
+ @register_lowering(symm_mem.reduce_scatter_out)
780
+ def _symm_mem_reduce_scatter_out(
781
+ inp: ir.TensorBox,
782
+ group_name: str,
783
+ split_last_dim: bool,
784
+ output: ir.TensorBox,
785
+ ):
786
+ inp = _maybe_realize_symm_mem(inp, group_name)
787
+ return pytree.tree_map(
788
+ ir.TensorBox.create,
789
+ ir.FallbackKernel.create(
790
+ symm_mem.reduce_scatter_out.default,
791
+ inp,
792
+ group_name,
793
+ split_last_dim,
794
+ output,
795
+ ),
796
+ )
797
+
798
+ @register_lowering(symm_mem.all_to_all_vdev)
799
+ def _symm_mem_all_to_all_vdev(
800
+ inp: ir.TensorBox,
801
+ out: ir.TensorBox,
802
+ in_splits: ir.TensorBox,
803
+ out_splits_offsets: ir.TensorBox,
804
+ group_name: str,
805
+ ):
806
+ inp = _maybe_realize_symm_mem(inp, group_name)
807
+ out = _maybe_realize_symm_mem(out, group_name)
808
+ ir.FallbackKernel.create(
809
+ symm_mem.all_to_all_vdev.default,
810
+ inp,
811
+ out,
812
+ in_splits,
813
+ out_splits_offsets,
814
+ group_name,
815
+ )
816
+ return None
817
+
818
+ @register_lowering(symm_mem.all_to_all_vdev_2d)
819
+ def _symm_mem_all_to_all_vdev_2d(
820
+ inp: ir.TensorBox,
821
+ out: ir.TensorBox,
822
+ in_splits: ir.TensorBox,
823
+ out_splits_offsets: ir.TensorBox,
824
+ group_name: str,
825
+ major_align=None,
826
+ ):
827
+ inp = _maybe_realize_symm_mem(inp, group_name)
828
+ out = _maybe_realize_symm_mem(out, group_name)
829
+ ir.FallbackKernel.create(
830
+ symm_mem.all_to_all_vdev_2d.default,
831
+ inp,
832
+ out,
833
+ in_splits,
834
+ out_splits_offsets,
835
+ group_name,
836
+ major_align,
837
+ )
838
+ return None
839
+
840
+ @register_lowering(symm_mem.all_to_all_vdev_2d_offset)
841
+ def _symm_mem_all_to_all_vdev_2d_offset(
842
+ inp: ir.TensorBox,
843
+ out: ir.TensorBox,
844
+ in_splits_offsets: ir.TensorBox,
845
+ out_splits_offsets: ir.TensorBox,
846
+ group_name: str,
847
+ ):
848
+ inp = _maybe_realize_symm_mem(inp, group_name)
849
+ out = _maybe_realize_symm_mem(out, group_name)
850
+ ir.FallbackKernel.create(
851
+ symm_mem.all_to_all_vdev_2d_offset.default,
852
+ inp,
853
+ out,
854
+ in_splits_offsets,
855
+ out_splits_offsets,
856
+ group_name,
857
+ )
858
+ return None
859
+
860
+ @register_lowering(symm_mem.tile_reduce)
861
+ def _symm_mem_tile_reduce(
862
+ in_tile: ir.TensorBox,
863
+ out_tile: ir.TensorBox,
864
+ root: int,
865
+ group_name: str,
866
+ reduce_op: str = "sum",
867
+ ):
868
+ in_tile = _maybe_realize_symm_mem(in_tile, group_name)
869
+ out_tile = _maybe_realize_symm_mem(out_tile, group_name)
870
+ ir.FallbackKernel.create(
871
+ symm_mem.tile_reduce.default,
872
+ in_tile,
873
+ out_tile,
874
+ root,
875
+ group_name,
876
+ reduce_op,
877
+ )
878
+ return None
879
+
880
+ @register_lowering(symm_mem.multi_root_tile_reduce)
881
+ def _symm_mem_multi_root_tile_reduce(
882
+ in_tiles, # list of TensorBox
883
+ out_tile: ir.TensorBox,
884
+ roots, # list of int
885
+ group_name: str,
886
+ reduce_op: str = "sum",
887
+ ):
888
+ for i, in_tile in enumerate(in_tiles):
889
+ in_tiles[i] = _maybe_realize_symm_mem(in_tile, group_name)
890
+ out_tile = _maybe_realize_symm_mem(out_tile, group_name)
891
+ ir.FallbackKernel.create(
892
+ symm_mem.multi_root_tile_reduce.default,
893
+ in_tiles,
894
+ out_tile,
895
+ roots,
896
+ group_name,
897
+ reduce_op,
898
+ )
899
+ return None
900
+
901
+ @register_lowering(symm_mem._low_contention_all_gather)
902
+ def _symm_mem_low_contention_all_gather(
903
+ inp: ir.TensorBox,
904
+ group_name: str,
905
+ ):
906
+ # Use _CollectiveKernel so that _WaitKernel.get_volatile_reads()
907
+ # can track the input's lifetime through wait_tensor, preventing
908
+ # the memory planner from reusing the input buffer while the
909
+ # backend stream is still reading it.
910
+ return _create_out_of_place(
911
+ symm_mem._low_contention_all_gather.default,
912
+ inp,
913
+ group_name,
914
+ )
915
+
916
+ @register_lowering(symm_mem._low_contention_all_gather_ce_multicast)
917
+ def _symm_mem_low_contention_all_gather_ce_multicast(
918
+ inp: ir.TensorBox,
919
+ group_name: "torch.distributed.distributed_c10d.GroupName",
920
+ ):
921
+ return _create_low_contention_ag_out(
922
+ symm_mem._low_contention_all_gather_ce_multicast_out.default,
923
+ inp,
924
+ group_name,
925
+ )
926
+
927
+ @register_lowering(symm_mem._low_contention_all_gather_ce_multicast_out)
928
+ def _symm_mem_low_contention_all_gather_ce_multicast_out(
929
+ inp: ir.TensorBox,
930
+ group_name: "torch.distributed.distributed_c10d.GroupName",
931
+ out: ir.TensorBox,
932
+ ):
933
+ inp.realize()
934
+ if can_realize_as_comm_buffer(out, ir.CommBufferType.SYMM_MEM):
935
+ realize_as_comm_buffer(out, ir.CommBufferType.SYMM_MEM, group_name)
936
+ else:
937
+ raise RuntimeError(
938
+ "_low_contention_all_gather_ce_multicast_out requires an "
939
+ "Inductor-owned output buffer that can be realized as symmetric "
940
+ "memory; this indicates an invalid lowering."
941
+ )
942
+ return pytree.tree_map(
943
+ ir.TensorBox.create,
944
+ ir.FallbackKernel.create(
945
+ symm_mem._low_contention_all_gather_ce_multicast_out.default,
946
+ inp,
947
+ group_name,
948
+ out,
949
+ ),
950
+ )
951
+
952
+ @register_lowering(symm_mem._low_contention_reduce_scatter)
953
+ def _symm_mem_low_contention_reduce_scatter(
954
+ inp: ir.TensorBox,
955
+ reduce_op: str,
956
+ group_name: str,
957
+ ):
958
+ # Use _CollectiveKernel so that _WaitKernel.get_volatile_reads()
959
+ # can track the input's lifetime through wait_tensor, preventing
960
+ # the memory planner from reusing the input buffer while the
961
+ # backend stream is still reading it.
962
+ return _create_out_of_place(
963
+ symm_mem._low_contention_reduce_scatter.default,
964
+ inp,
965
+ reduce_op,
966
+ group_name,
967
+ )
.venv/lib/python3.12/site-packages/torch/_inductor/comms.py ADDED
@@ -0,0 +1,2402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mypy: allow-untyped-defs
2
+ # pyre-strict
3
+ from __future__ import annotations
4
+
5
+ import heapq
6
+ import importlib
7
+ import itertools
8
+ import logging
9
+ import sys
10
+ from collections import defaultdict
11
+ from dataclasses import dataclass
12
+ from typing import Any, TYPE_CHECKING
13
+
14
+ import torch
15
+ from torch._logging import trace_structured
16
+ from torch.utils._ordered_set import OrderedSet
17
+
18
+ from . import config, config_comms, ir
19
+ from .dependencies import WeakDep
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from .ir import IRNode, Operation
24
+
25
+ from .memory import (
26
+ estimate_peak_memory_allocfree,
27
+ FreeableInputBuffer,
28
+ get_freeable_input_buf,
29
+ SNodeMemory,
30
+ )
31
+ from .utils import contains_collective, contains_wait, is_fallback_op, is_wait
32
+ from .virtualized import V
33
+
34
+
35
+ log = logging.getLogger(__name__)
36
+ overlap_log = torch._logging.getArtifactLogger(__name__, "overlap")
37
+
38
+ if TYPE_CHECKING:
39
+ from torch._inductor.scheduler import BaseSchedulerNode
40
+
41
+
42
+ def align_runtime_estimations_across_all_distributed_ranks(
43
+ snodes: list[BaseSchedulerNode],
44
+ ):
45
+ runtime_estimations = [snode.get_estimated_runtime() for snode in snodes]
46
+
47
+ import torch.distributed as dist
48
+ from torch.distributed.distributed_c10d import _get_default_group
49
+
50
+ world_size = dist.get_world_size()
51
+ pg = _get_default_group()
52
+ gathered_runtime_estimations: list[list[float]] = [[] for _ in range(world_size)]
53
+ dist.all_gather_object(
54
+ gathered_runtime_estimations,
55
+ runtime_estimations,
56
+ pg,
57
+ )
58
+
59
+ lengths = OrderedSet([len(e) for e in gathered_runtime_estimations])
60
+ if len(lengths) != 1:
61
+ log.warning(
62
+ "Different ranks have different numbers of scheduler nodes (%s), "
63
+ "skipping runtime estimation alignment",
64
+ [len(e) for e in gathered_runtime_estimations],
65
+ )
66
+ for idx, snode in enumerate(snodes):
67
+ snode.override_estimated_runtime = runtime_estimations[idx]
68
+ return
69
+
70
+ median_runtime_estimations = torch.median(
71
+ torch.tensor(gathered_runtime_estimations), dim=0
72
+ ).values.tolist()
73
+
74
+ for idx, snode in enumerate(snodes):
75
+ snode.override_estimated_runtime = median_runtime_estimations[idx]
76
+
77
+
78
+ def sink_waits(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
79
+ """
80
+ Greedily schedules waits as late as possible.
81
+ """
82
+ return _schedule_for_comm(
83
+ snodes, raise_comms=False, sink_waits=True, reorder_for_overlap=False
84
+ )
85
+
86
+
87
+ def raise_comms(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
88
+ """
89
+ Greedily schedules comms as early as possible.
90
+ """
91
+ return _schedule_for_comm(
92
+ snodes, raise_comms=True, sink_waits=False, reorder_for_overlap=False
93
+ )
94
+
95
+
96
+ def reorder_compute_for_overlap(
97
+ snodes: list[BaseSchedulerNode],
98
+ ) -> list[BaseSchedulerNode]:
99
+ """
100
+ This achieves the following overall scheduling procedure:
101
+ Step 1: Given that we've currently scheduled comm N, we now schedule all compute nodes
102
+ that are required for comm N + 1 but do not depend on comm N, to run at the same time with comm N.
103
+ Step 2: If all those compute nodes are sufficient to overlap comm N, we're done.
104
+ Otherwise, we now need to look elsewhere to find compute that overlaps with comm N.
105
+ We prioritize compute nodes that are needed sooner.
106
+ Step 3: We schedule the compute nodes dependent on comm N and required for comm N + 1.
107
+ Step 4: We schedule comm N + 1.
108
+ Repeat this for subsequent comm nodes.
109
+ """
110
+ return _schedule_for_comm(
111
+ snodes, raise_comms=True, sink_waits=True, reorder_for_overlap=True
112
+ )
113
+
114
+
115
+ def reorder_communication_preserving_peak_memory(
116
+ snodes: list[BaseSchedulerNode],
117
+ ) -> list[BaseSchedulerNode]:
118
+ """
119
+ Reorders communication ops relative to computation ops to improve communication-compute overlapping and hide comm
120
+ latency. Stops moving a particular op if it reaches a point that would have increased the peak memory footprint.
121
+
122
+ Currently, follows these heuristics (subject to change or tune):
123
+ - never reorders collectives relative to one another, for SPMD safety
124
+ - has an option for per-collective prefetch limit, but does not enable it by default
125
+ - limits the total number of reorder steps to some factor of the graph size to prevent worst-case quadratic
126
+ performance
127
+
128
+ Prerequisite: sink_comms_and_waits - ensure comm and wait nodes are scheduled as late as possible, respecting data
129
+ dependencies. That allows reorder_communication_preserving_peak_memory to take a best case peak-memory snapshot,
130
+ and then monotonically improve latency by moving collectives backward in time.
131
+
132
+ Peak memory impact is computed in an iterative fashion. First, memory use at each timestep is computed, and global
133
+ peak memory is computed as a max over timesteps. Then, when swapping any two adjacent nodes, only the curr-memory
134
+ for the earlier of the nodes after the swap is affected. This enables checking step by step whether a swap is
135
+ peak-memory-safe, and bailing out if not. Example:
136
+
137
+ 0 n0 C0
138
+ 1 n1 C0 + Allocs(n1) - Frees(n1)
139
+ 2 n2 C0 + Allocs(n1) - Frees(n1) + Allocs(n2) - Frees(n2)
140
+
141
+ 0 n0 C0
142
+ 1 n2 C0 + Allocs(n2) - Frees(n2) <-- After moving n2 to Time 1, only time1 memory changes
143
+ 2 n1 C0 + Allocs(n2) - Frees(n2) + Allocs(n1) - Frees(n1)
144
+
145
+ """
146
+ reordered_snodes, node_stats = (
147
+ _reorder_communication_preserving_peak_memory_internal(snodes)
148
+ )
149
+
150
+ return reordered_snodes
151
+
152
+
153
+ @dataclass
154
+ class ReorderInfo:
155
+ """
156
+ Debug info describing how an individual snode was reordered
157
+ """
158
+
159
+ limiting_factor: str = "None"
160
+ moves: int = 0
161
+ grouped: int = 0
162
+ grouped_info: str = ""
163
+ comm_time: float = -1.0
164
+ comp_time: float = -1.0
165
+ initial_exposed: float = -1.0
166
+ final_exposed: float = -1.0
167
+ overlap_info: str = "None"
168
+
169
+ @property
170
+ def improvement(self):
171
+ return self.initial_exposed - self.final_exposed
172
+
173
+
174
+ def is_gemm_like(node: IRNode | Operation | None) -> bool:
175
+ if node is None:
176
+ return False
177
+
178
+ if is_fallback_op(
179
+ node, # type: ignore[arg-type]
180
+ torch.ops.aten._scaled_dot_product_flash_attention.default,
181
+ ):
182
+ return True
183
+
184
+ if (
185
+ python_kernel_name := getattr(node, "python_kernel_name", None)
186
+ ) and "extern_kernels" in python_kernel_name:
187
+ return True
188
+ return False
189
+
190
+
191
+ def contains_gemm_like(snode: BaseSchedulerNode) -> bool:
192
+ from torch._inductor.scheduler import GroupedSchedulerNode
193
+
194
+ if isinstance(snode, GroupedSchedulerNode):
195
+ return any(contains_gemm_like(x) for x in snode.snodes)
196
+ else:
197
+ return is_gemm_like(snode.node)
198
+
199
+
200
+ def _temp_group_visit_leaves(snode: BaseSchedulerNode, fn):
201
+ from torch._inductor.scheduler import GroupedSchedulerNode
202
+
203
+ if isinstance(snode, GroupedSchedulerNode) and snode.temp_grouping:
204
+ for _snode in snode.snodes:
205
+ fn(_snode)
206
+ else:
207
+ fn(snode)
208
+
209
+
210
+ def _group_name(snode, with_bufs=False) -> str:
211
+ ret = ""
212
+ for n in snode.snodes:
213
+ if ret:
214
+ ret += "_"
215
+ ret += n.get_name()
216
+ if with_bufs:
217
+ ret += f"{list(snode.get_buffer_names())}"
218
+ return ret
219
+
220
+
221
+ def _is_fake_dep(d):
222
+ return isinstance(d, WeakDep) and d.is_fake
223
+
224
+
225
+ def _group_names(gns: list[BaseSchedulerNode]) -> str:
226
+ return "~".join([gn.get_name() for gn in gns])
227
+
228
+
229
+ def _initialize_memory_tracking(snodes, graph_inputs=None, graph_outputs=None):
230
+ """Initialize memory tracking data structures"""
231
+ if graph_inputs is None:
232
+ graph_inputs = OrderedSet(V.graph.graph_inputs.keys())
233
+ if graph_outputs is None:
234
+ graph_outputs = OrderedSet(V.graph.get_output_names())
235
+
236
+ name_to_freeable_input_buf = get_freeable_input_buf(snodes, graph_inputs)
237
+ peak_memory, snodes_curr_memory, snodes_allocfree, buf_to_snode_last_use = (
238
+ estimate_peak_memory_allocfree(
239
+ snodes, name_to_freeable_input_buf, graph_outputs
240
+ )
241
+ )
242
+ _curr_memory = dict(zip(snodes, snodes_curr_memory))
243
+ # pyrefly: ignore [unsupported-operation]
244
+ _curr_memory[None] = (0, 0)
245
+
246
+ # Build candidate buffer map for optimization
247
+ candidate_buffer_map = _build_candidate_buffer_map(buf_to_snode_last_use)
248
+
249
+ return (
250
+ peak_memory,
251
+ _curr_memory,
252
+ snodes_allocfree,
253
+ buf_to_snode_last_use,
254
+ name_to_freeable_input_buf,
255
+ candidate_buffer_map,
256
+ )
257
+
258
+
259
+ def _initialize_double_linked_list(
260
+ snodes: list[BaseSchedulerNode],
261
+ ) -> tuple[
262
+ dict[BaseSchedulerNode, BaseSchedulerNode | None],
263
+ dict[BaseSchedulerNode, BaseSchedulerNode | None],
264
+ BaseSchedulerNode,
265
+ ]:
266
+ """Create double-linked list structure from snodes"""
267
+ _prev = {}
268
+ _next = {}
269
+ for i, snode in enumerate(snodes):
270
+ _prev[snode] = snodes[i - 1] if i > 0 else None
271
+ _next[snode] = snodes[i + 1] if i < len(snodes) - 1 else None
272
+ _head = snodes[0]
273
+ return _prev, _next, _head
274
+
275
+
276
+ def _build_candidate_buffer_map(
277
+ buf_to_snode_last_use: dict,
278
+ ) -> dict[BaseSchedulerNode, OrderedSet]:
279
+ """
280
+ Build inverted index: node -> set of buffers where node appears in successors.
281
+
282
+ This optimization reduces buffer iteration from O(total_buffers) to O(buffers_per_node).
283
+ Since buffer successors are immutable during reordering, this map doesn't need updates.
284
+
285
+ Returns:
286
+ dict mapping each node to the set of buffers that have this node in their successors
287
+ """
288
+ node_to_candidate_bufs: dict[BaseSchedulerNode, OrderedSet] = defaultdict(
289
+ OrderedSet
290
+ )
291
+
292
+ for buf in buf_to_snode_last_use:
293
+ # Add to every successor node's buffer set
294
+ for succ_node in buf.mpi_buffer.succ_nodes:
295
+ node_to_candidate_bufs[succ_node].add(buf)
296
+
297
+ return dict(node_to_candidate_bufs)
298
+
299
+
300
+ def _precompute_node_output_sets(
301
+ snodes: list[BaseSchedulerNode],
302
+ ) -> dict[BaseSchedulerNode, OrderedSet[str]]:
303
+ """
304
+ Pre-compute output name sets for all nodes.
305
+
306
+ This optimization avoids creating OrderedSet objects repeatedly during
307
+ exposed time calculations.
308
+
309
+ Returns:
310
+ dict mapping each node to a set of its output names
311
+ """
312
+ return {
313
+ snode: OrderedSet(o.get_name() for o in snode.get_outputs()) for snode in snodes
314
+ }
315
+
316
+
317
+ def _op_runtime_estimate_mult(snode):
318
+ # Apply multipliers for faster experimentation.
319
+ # TODO(ivankobzarev): Remove after confirmation that runtime estimations are correct.
320
+ if contains_collective(snode):
321
+ return config_comms.reorder_sink_runtime_estimations_comm_mult
322
+
323
+ return config_comms.reorder_sink_runtime_estimations_non_comm_mult
324
+
325
+
326
+ def is_async_collective(snode):
327
+ """
328
+ Filtering out ops that contain Collective and Wait inside and considered as Collectives.
329
+ See contains_collective function.
330
+ If the op contains Wait inside - consider as Synchronous compute.
331
+ """
332
+ if python_kernel_name := getattr(snode.node, "python_kernel_name", None):
333
+ if "torch.ops._dtensor.shard_dim_alltoall.default" in python_kernel_name:
334
+ return False
335
+
336
+ return True
337
+
338
+
339
+ def contains_async_collective(snode):
340
+ return contains_collective(snode, is_async_collective)
341
+
342
+
343
+ def _group_nodes_from_linked_list(
344
+ head: BaseSchedulerNode | None,
345
+ tail: BaseSchedulerNode | None,
346
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
347
+ ) -> list[BaseSchedulerNode]:
348
+ """
349
+ Traverse doubly-linked list from head to tail and return nodes as a list.
350
+
351
+ Args:
352
+ head: Starting node of the segment
353
+ tail: Ending node of the segment (inclusive)
354
+ next_dict: Dictionary mapping each node to its next node
355
+
356
+ Returns:
357
+ List of nodes from head to tail (inclusive)
358
+ """
359
+ ret = []
360
+ n = head
361
+ while True:
362
+ if n is not None:
363
+ ret.append(n)
364
+ if n == tail:
365
+ break
366
+ n = next_dict[n] # type: ignore[index]
367
+ return ret
368
+
369
+
370
+ def _is_corresponding_collective_wait(
371
+ collective_snode: BaseSchedulerNode,
372
+ wait_snode: BaseSchedulerNode,
373
+ node_output_sets: dict[BaseSchedulerNode, frozenset[str]],
374
+ node_dep_sets: dict[BaseSchedulerNode, frozenset[str]],
375
+ ) -> bool:
376
+ """
377
+ Check if a wait node corresponds to a given collective node.
378
+ Uses pre-computed sets for O(1) lookup.
379
+ """
380
+ collective_outs = node_output_sets[collective_snode]
381
+ unmet_deps = node_dep_sets[wait_snode]
382
+ return bool(unmet_deps & collective_outs)
383
+
384
+
385
+ def _coll_exposed_communication_time(
386
+ collective_snode: BaseSchedulerNode,
387
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
388
+ runtimes: dict[BaseSchedulerNode, float],
389
+ node_output_sets: dict[BaseSchedulerNode, frozenset[str]],
390
+ node_dep_sets: dict[BaseSchedulerNode, frozenset[str]],
391
+ ) -> tuple[float, float, str]:
392
+ """
393
+ Calculate exposed communication time by iterating directly over linked list.
394
+ Avoids O(N) list construction for each call.
395
+
396
+ The collective_snode is the starting point, iteration continues via next_dict.
397
+ """
398
+ comm_time = runtimes[collective_snode]
399
+ comp_time = 0.0
400
+ collective_outs = node_output_sets[collective_snode]
401
+ overlap_info = ""
402
+ collectives_found: list[BaseSchedulerNode] = []
403
+
404
+ snode = next_dict[collective_snode]
405
+ while snode is not None:
406
+ unmet_deps = node_dep_sets[snode]
407
+
408
+ if unmet_deps & collective_outs:
409
+ overlap_info += f"->W[{snode.get_name()}]"
410
+ break
411
+
412
+ if contains_collective(snode):
413
+ if not contains_async_collective(snode):
414
+ break
415
+ else:
416
+ collectives_found.append(snode)
417
+ snode = next_dict[snode]
418
+ continue
419
+ if contains_wait(snode):
420
+ has_wait_for_collectives_found = False
421
+ for _coll in collectives_found:
422
+ if _is_corresponding_collective_wait(
423
+ collective_snode, snode, node_output_sets, node_dep_sets
424
+ ):
425
+ has_wait_for_collectives_found = True
426
+ break
427
+ if has_wait_for_collectives_found:
428
+ break
429
+
430
+ comp_time_before = comp_time
431
+
432
+ def accumulate_time(_snode: BaseSchedulerNode) -> None:
433
+ nonlocal comp_time
434
+ comp_time += runtimes[_snode]
435
+
436
+ _temp_group_visit_leaves(snode, accumulate_time)
437
+ comp_time_after = comp_time
438
+ overlap_info += f"+{snode.get_name()}[{comp_time_after - comp_time_before}]"
439
+
440
+ snode = next_dict[snode]
441
+
442
+ return comm_time, comp_time, overlap_info
443
+
444
+
445
+ def _wait_exposed_communication_time(
446
+ wait_snode: BaseSchedulerNode,
447
+ head: BaseSchedulerNode,
448
+ prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
449
+ runtimes: dict[BaseSchedulerNode, float],
450
+ node_output_sets: dict[BaseSchedulerNode, frozenset[str]],
451
+ node_dep_sets: dict[BaseSchedulerNode, frozenset[str]],
452
+ ) -> tuple[float, float, str]:
453
+ """
454
+ Calculate exposed communication time for a wait operation by iterating
455
+ directly over linked list backwards. Avoids O(N) list construction.
456
+
457
+ Iterates from wait_snode backwards using prev_dict to find corresponding collective.
458
+ """
459
+ comm_time = 0.0
460
+ comp_time = 0.0
461
+ overlap_info = ""
462
+ waits_found: list[BaseSchedulerNode] = []
463
+
464
+ snode = prev_dict[wait_snode]
465
+ while snode is not None:
466
+ if contains_wait(snode):
467
+ waits_found.append(snode)
468
+ if contains_collective(snode):
469
+ if _is_corresponding_collective_wait(
470
+ snode, wait_snode, node_output_sets, node_dep_sets
471
+ ):
472
+ comm_time = runtimes[snode]
473
+ overlap_info += f"->C[{snode.get_name()}]"
474
+ break
475
+
476
+ if not contains_async_collective(snode):
477
+ comp_time = 0.0
478
+ snode = prev_dict[snode]
479
+ continue
480
+ else:
481
+ for w in waits_found:
482
+ if _is_corresponding_collective_wait(
483
+ snode, w, node_output_sets, node_dep_sets
484
+ ):
485
+ comp_time = 0.0
486
+ break # inner loop break
487
+ snode = prev_dict[snode]
488
+ continue
489
+
490
+ comp_time_before = comp_time
491
+
492
+ def accumulate_time(_snode: BaseSchedulerNode) -> None:
493
+ nonlocal comp_time
494
+ comp_time += runtimes[_snode]
495
+
496
+ _temp_group_visit_leaves(snode, accumulate_time)
497
+ comp_time_after = comp_time
498
+ overlap_info += f"+{snode.get_name()}[{comp_time_after - comp_time_before}]"
499
+
500
+ snode = prev_dict[snode]
501
+
502
+ return comm_time, comp_time, overlap_info
503
+
504
+
505
+ def _perform_double_linked_list_swap(
506
+ candidate: BaseSchedulerNode,
507
+ group_head: BaseSchedulerNode,
508
+ group_tail: BaseSchedulerNode,
509
+ prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
510
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
511
+ head: BaseSchedulerNode,
512
+ ) -> BaseSchedulerNode:
513
+ """
514
+ Swap positions of candidate and group in doubly-linked list.
515
+
516
+ Transforms:
517
+ candidate_prev -> candidate -> group_head...group_tail -> group_tail_next
518
+ Into:
519
+ candidate_prev -> group_head...group_tail -> candidate -> group_tail_next
520
+
521
+ Args:
522
+ candidate: Node to swap with group
523
+ group_head: First node of group
524
+ group_tail: Last node of group
525
+ prev_dict: Dictionary mapping nodes to their previous nodes
526
+ next_dict: Dictionary mapping nodes to their next nodes
527
+ head: Current head of the linked list
528
+
529
+ Returns:
530
+ New head of the linked list (may change if candidate was the head)
531
+ """
532
+ # 0: Update candidate's previous node
533
+ candidate_prev = prev_dict[candidate]
534
+ if candidate_prev:
535
+ next_dict[candidate_prev] = group_head
536
+ prev_dict[group_head] = candidate_prev
537
+
538
+ # 2: Update group_tail's next node
539
+ group_tail_next = next_dict[group_tail]
540
+ if group_tail_next:
541
+ prev_dict[group_tail_next] = candidate
542
+ next_dict[candidate] = group_tail_next
543
+
544
+ # 1: Link group_tail to candidate
545
+ prev_dict[candidate] = group_tail
546
+ next_dict[group_tail] = candidate
547
+
548
+ # Update head if candidate was the head
549
+ if head == candidate:
550
+ return group_head
551
+ return head
552
+
553
+
554
+ def _calculate_potential_peak_memory_reorder(
555
+ candidate: BaseSchedulerNode,
556
+ gns: list[BaseSchedulerNode],
557
+ group_tail: BaseSchedulerNode,
558
+ group_peak_memory: int,
559
+ candidate_delta_mem: int,
560
+ candidate_allocfree: SNodeMemory,
561
+ group_n_to_bufs_after_swap_dealloc_by_candidate: dict,
562
+ curr_memory: dict,
563
+ ) -> tuple[int, dict[BaseSchedulerNode, int]]:
564
+ """
565
+ Calculate potential peak memory after swapping candidate with group (reorder version).
566
+
567
+ Computes new memory levels for all affected nodes and returns the potential
568
+ peak memory along with cached post-allocation memory values for each node.
569
+
570
+ Args:
571
+ candidate: Node being moved
572
+ gns: Group nodes
573
+ group_tail: Last node of group
574
+ group_peak_memory: Current peak memory within the group
575
+ candidate_delta_mem: Net memory change from candidate (alloc - free)
576
+ candidate_allocfree: Candidate's allocation/free info
577
+ group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate
578
+ curr_memory: Current memory state dict
579
+
580
+ Returns:
581
+ Tuple of (potential_peak_memory, post_alloc_update_dict)
582
+ """
583
+ # Caching calculations of memory for group nodes and candidate,
584
+ # to apply without recalculation after swap.
585
+ _post_alloc_update: dict[BaseSchedulerNode, int] = {}
586
+ potential_peak: int = 0
587
+ if not group_n_to_bufs_after_swap_dealloc_by_candidate:
588
+ # Not accounting for buffers last use change
589
+ potential_peak = max(
590
+ group_peak_memory - candidate_delta_mem,
591
+ curr_memory[group_tail][1]
592
+ - candidate_delta_mem
593
+ + candidate_allocfree.size_alloc,
594
+ )
595
+ return potential_peak, _post_alloc_update
596
+
597
+ # If candidate will be after group, the starting memory level of group nodes
598
+ # changes to the -(candidate.size_alloc - candidate.size_free)
599
+ mem_after_reorder_delta: int = -candidate_delta_mem
600
+ for gn in gns:
601
+ gn_post_alloc_mem = curr_memory[gn][0] + mem_after_reorder_delta
602
+ _post_alloc_update[gn] = gn_post_alloc_mem
603
+ potential_peak = max(potential_peak, gn_post_alloc_mem)
604
+
605
+ bufs = group_n_to_bufs_after_swap_dealloc_by_candidate.get(gn)
606
+ if bufs is not None:
607
+ for buf in bufs:
608
+ # Candidate will deallocate those buffers
609
+ mem_after_reorder_delta += buf.mpi_buffer.size_free
610
+
611
+ candidate_mem_post_alloc = (
612
+ curr_memory[group_tail][1]
613
+ + mem_after_reorder_delta
614
+ + candidate_allocfree.size_alloc
615
+ )
616
+ _post_alloc_update[candidate] = candidate_mem_post_alloc
617
+ potential_peak = max(potential_peak, candidate_mem_post_alloc)
618
+ return potential_peak, _post_alloc_update
619
+
620
+
621
+ def _update_memory_tracking_after_swap_reorder(
622
+ candidate: BaseSchedulerNode,
623
+ gns: list[BaseSchedulerNode],
624
+ group_tail: BaseSchedulerNode,
625
+ candidate_delta_mem: int,
626
+ candidate_allocfree: SNodeMemory,
627
+ group_n_to_bufs_after_swap_dealloc_by_candidate: dict,
628
+ post_alloc_update: dict[BaseSchedulerNode, int],
629
+ curr_memory: dict,
630
+ buf_to_snode_last_use: dict,
631
+ snodes_allocfree: dict,
632
+ ) -> None:
633
+ """
634
+ Update memory tracking structures after swap (reorder version).
635
+
636
+ Updates curr_memory, buf_to_snode_last_use, and snodes_allocfree dictionaries
637
+ to reflect the new memory state after swapping candidate with group.
638
+
639
+ Args:
640
+ candidate: Node that was moved
641
+ gns: Group nodes
642
+ group_tail: Last node of group
643
+ candidate_delta_mem: Net memory change from candidate (alloc - free)
644
+ candidate_allocfree: Candidate's allocation/free info
645
+ group_n_to_bufs_after_swap_dealloc_by_candidate: Buffers whose deallocation moves to candidate
646
+ post_alloc_update: Cached post-allocation memory values
647
+ curr_memory: Current memory state dict (mutated)
648
+ buf_to_snode_last_use: Buffer to last-use node mapping (mutated)
649
+ snodes_allocfree: Node allocation/free info dict (mutated)
650
+ """
651
+ if not group_n_to_bufs_after_swap_dealloc_by_candidate:
652
+ for gn in gns:
653
+ cm = curr_memory[gn]
654
+ curr_memory[gn] = (
655
+ cm[0] - candidate_delta_mem,
656
+ cm[1] - candidate_delta_mem,
657
+ )
658
+ _candidate_post_alloc_mem = (
659
+ curr_memory[group_tail][1] + candidate_allocfree.size_alloc
660
+ )
661
+ _candidate_post_free_mem = (
662
+ _candidate_post_alloc_mem - candidate_allocfree.size_free
663
+ )
664
+ curr_memory[candidate] = (
665
+ _candidate_post_alloc_mem,
666
+ _candidate_post_free_mem,
667
+ )
668
+ return
669
+
670
+ # Candidate becomes last use of some bufs
671
+ for bufs in group_n_to_bufs_after_swap_dealloc_by_candidate.values():
672
+ for buf in bufs:
673
+ buf_to_snode_last_use[buf] = candidate
674
+
675
+ size_free_to_move_to_candidate_sum: int = 0
676
+ for n in gns:
677
+ _gn_post_alloc_mem: int = post_alloc_update[n]
678
+ size_free_to_move_to_candidate: int = sum(
679
+ buf.mpi_buffer.size_free
680
+ for buf in group_n_to_bufs_after_swap_dealloc_by_candidate[n]
681
+ )
682
+ size_free_to_move_to_candidate_sum += size_free_to_move_to_candidate
683
+ # group node does not deallocate this after swap
684
+ snodes_allocfree[n].size_free -= size_free_to_move_to_candidate
685
+ gn_post_free_mem: int = _gn_post_alloc_mem - snodes_allocfree[n].size_free
686
+ curr_memory[n] = (_gn_post_alloc_mem, gn_post_free_mem)
687
+ _candidate_post_alloc_mem = post_alloc_update[candidate]
688
+ snodes_allocfree[candidate].size_free += size_free_to_move_to_candidate_sum
689
+ candidate_post_free_mem = (
690
+ _candidate_post_alloc_mem - snodes_allocfree[candidate].size_free
691
+ )
692
+ curr_memory[candidate] = (
693
+ _candidate_post_alloc_mem,
694
+ candidate_post_free_mem,
695
+ )
696
+
697
+
698
+ def _find_buffers_with_changed_last_use(
699
+ candidate: BaseSchedulerNode,
700
+ gns: list[BaseSchedulerNode],
701
+ buf_to_snode_last_use: dict,
702
+ candidate_buffer_map: dict[BaseSchedulerNode, OrderedSet],
703
+ ) -> dict[BaseSchedulerNode, list[FreeableInputBuffer | Any]]:
704
+ """
705
+ Find buffers whose last use will change after swapping candidate with group.
706
+
707
+ When we swap [candidate [group]] to [[group] candidate], some buffers that
708
+ were last used by a group node will now be last used by candidate instead.
709
+ This affects memory deallocation timing.
710
+
711
+ Args:
712
+ candidate: The node being moved
713
+ gns: Group nodes being swapped with candidate
714
+ buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
715
+ candidate_buffer_map: Pre-computed map of node -> buffers using that node
716
+
717
+ Returns:
718
+ Dict mapping group nodes to buffers that will change their last-use node
719
+ """
720
+ group_n_to_bufs_after_swap_dealloc_by_candidate: dict[
721
+ BaseSchedulerNode, list[FreeableInputBuffer | Any]
722
+ ] = defaultdict(list)
723
+
724
+ # Optimization: only check buffers where candidate is a successor
725
+ # Reduces from O(all_buffers) to O(buffers_per_candidate)
726
+ candidate_bufs = candidate_buffer_map.get(candidate, OrderedSet())
727
+ gns_set = OrderedSet(gns) # O(1) membership testing
728
+
729
+ for buf in candidate_bufs:
730
+ snode_last_use = buf_to_snode_last_use[buf]
731
+ if snode_last_use in gns_set:
732
+ group_n_to_bufs_after_swap_dealloc_by_candidate[snode_last_use].append(buf)
733
+
734
+ return group_n_to_bufs_after_swap_dealloc_by_candidate
735
+
736
+
737
+ def _is_node_groupable_for_reorder(
738
+ candidate: BaseSchedulerNode,
739
+ ) -> tuple[bool, str | None]:
740
+ """
741
+ Check if a candidate node can be grouped with collective during reordering.
742
+
743
+ This pass processes collectives left to right, so we avoid grouping with
744
+ already-processed collectives based on configuration.
745
+
746
+ Args:
747
+ candidate: Node to check for groupability
748
+
749
+ Returns:
750
+ Tuple of (is_groupable, reason_if_not_groupable)
751
+ """
752
+ # This pass processes collectives left to right,
753
+ # Do not group with processed collectives.
754
+ # Leaving config for experimentation in 2D
755
+ if not config_comms.reorder_iterative_group_with_collectives:
756
+ if contains_async_collective(candidate):
757
+ return (
758
+ False,
759
+ f"candidate contains_collective {candidate.get_name()}",
760
+ )
761
+ if not config_comms.reorder_iterative_use_runtime_estimations:
762
+ if contains_gemm_like(candidate):
763
+ return False, "contains_gemm_like"
764
+ return True, None
765
+
766
+
767
+ def _format_and_log_reordering_stats(
768
+ stats: dict[BaseSchedulerNode, ReorderInfo],
769
+ head: BaseSchedulerNode,
770
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
771
+ original_snodes_num: int,
772
+ peak_memory: int,
773
+ name_to_freeable_input_buf: dict,
774
+ graph_outputs: OrderedSet[str],
775
+ ) -> list[BaseSchedulerNode]:
776
+ """
777
+ Format reordering statistics, log them, and return final node list.
778
+
779
+ Computes improvement metrics, creates a formatted table (using tabulate if
780
+ available), validates the reordered node count, recalculates peak memory,
781
+ and logs all information.
782
+
783
+ Args:
784
+ stats: Per-node reordering statistics
785
+ head: Head of the reordered linked list
786
+ next_dict: Linked list next pointers
787
+ original_snodes_num: Original number of nodes (for validation)
788
+ peak_memory: Initial peak memory before reordering
789
+ name_to_freeable_input_buf: Buffer memory tracking info
790
+ graph_outputs: Graph output names
791
+
792
+ Returns:
793
+ Final reordered list of scheduler nodes
794
+ """
795
+ node_stats = stats
796
+ improvement = {snode: node_stats[snode].improvement for snode in node_stats}
797
+ total_improvement = sum([improvement[snode] for snode in improvement])
798
+ total_moves = sum([node_stats[snode].moves for snode in node_stats])
799
+
800
+ reorder_log_str = (
801
+ f"reorder_communication_preserving_peak_memory improved overlap by {total_improvement} ns"
802
+ f" after {total_moves} reorders.\n"
803
+ )
804
+ headers = [
805
+ "Collective node",
806
+ "comm_time(us)",
807
+ "comp_time(us)",
808
+ "initial exposed(us)",
809
+ "final exposed(us)",
810
+ "improvement(us)",
811
+ "limiting factor",
812
+ "moves",
813
+ "grouped",
814
+ "grouped_info",
815
+ "overlap_info",
816
+ ]
817
+ rows = [
818
+ [
819
+ node_summary(snode),
820
+ node_info.comm_time / 1e3,
821
+ node_info.comp_time / 1e3,
822
+ node_info.initial_exposed / 1e3,
823
+ node_info.final_exposed / 1e3,
824
+ node_info.improvement / 1e3,
825
+ node_info.limiting_factor,
826
+ node_info.moves,
827
+ node_info.grouped,
828
+ node_info.grouped_info,
829
+ node_info.overlap_info,
830
+ ]
831
+ for snode, node_info in node_stats.items()
832
+ ]
833
+ if importlib.util.find_spec("tabulate"):
834
+ from tabulate import tabulate
835
+
836
+ reorder_log_str += tabulate(
837
+ rows,
838
+ headers=headers,
839
+ )
840
+ else:
841
+ reorder_log_str += (
842
+ "Please `pip install tabulate` to nicely render overlap stats.\n"
843
+ )
844
+ reorder_log_str += str(headers) + "\n"
845
+ reorder_log_str += "\n".join(map(str, rows))
846
+
847
+ new_snodes = _group_nodes_from_linked_list(head, None, next_dict)
848
+ if len(new_snodes) != original_snodes_num:
849
+ raise AssertionError(
850
+ f"expected {original_snodes_num} nodes, got {len(new_snodes)}"
851
+ )
852
+ new_peak_memory, _, _, _ = estimate_peak_memory_allocfree(
853
+ new_snodes, name_to_freeable_input_buf, graph_outputs
854
+ )
855
+ reorder_log_str += f"\n peak_memory_before:{peak_memory}"
856
+ reorder_log_str += f"\n peak_memory_after:{new_peak_memory}"
857
+
858
+ overlap_log.info(reorder_log_str)
859
+ trace_structured(
860
+ "artifact",
861
+ metadata_fn=lambda: {
862
+ "name": "reorder_communication_preserving_peak_memory",
863
+ "encoding": "string",
864
+ },
865
+ payload_fn=lambda: reorder_log_str,
866
+ )
867
+
868
+ return new_snodes
869
+
870
+
871
+ def _reorder_communication_preserving_peak_memory_internal(
872
+ snodes: list[BaseSchedulerNode],
873
+ ) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, ReorderInfo]]:
874
+ """
875
+ Internal testing helper that also returns debug info.
876
+ Returns:
877
+ - reordered snodes list
878
+ - dict {snode: ReorderInfo}
879
+ """
880
+ has_collectives = False
881
+ for snode in snodes:
882
+ if contains_collective(snode):
883
+ has_collectives = True
884
+ break
885
+ if not has_collectives:
886
+ return snodes, {}
887
+
888
+ original_snodes_num = len(snodes)
889
+ # heuristic to avoid degenerating to quadratic time
890
+ graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
891
+ graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
892
+ (
893
+ peak_memory,
894
+ _curr_memory,
895
+ snodes_allocfree,
896
+ buf_to_snode_last_use,
897
+ name_to_freeable_input_buf,
898
+ candidate_buffer_map,
899
+ ) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs)
900
+
901
+ runtimes: dict[BaseSchedulerNode, float] = {
902
+ snode: estimate_op_runtime(snode) * _op_runtime_estimate_mult(snode)
903
+ for snode in snodes
904
+ }
905
+
906
+ # Pre-compute output and dependency sets for O(1) lookup instead of O(N) creation per iteration
907
+ node_output_sets: dict[BaseSchedulerNode, frozenset[str]] = {
908
+ snode: frozenset(o.get_name() for o in snode.get_outputs()) for snode in snodes
909
+ }
910
+ node_dep_sets: dict[BaseSchedulerNode, frozenset[str]] = {
911
+ snode: frozenset(
912
+ d.name for d in snode.unmet_dependencies if not _is_fake_dep(d)
913
+ )
914
+ for snode in snodes
915
+ }
916
+
917
+ # debug stats
918
+ stats: dict[BaseSchedulerNode, ReorderInfo] = {}
919
+
920
+ total_moves = 0
921
+
922
+ _prev, _next, _head = _initialize_double_linked_list(snodes)
923
+
924
+ debug_num_collectives_to_reorder: int | None = (
925
+ config_comms.reorder_iterative_debug_limit_to_reorder
926
+ )
927
+
928
+ num_processed_collectives: int = 0
929
+ curr: BaseSchedulerNode | None = _head
930
+ debug_iterative_memory_recompute = (
931
+ config_comms.reorder_iterative_debug_memory_recompute
932
+ )
933
+ iterative_recompute_error = False
934
+
935
+ while curr is not None and _next[curr] is not None:
936
+ _next_curr = _next[curr]
937
+ if iterative_recompute_error:
938
+ break
939
+
940
+ if not contains_async_collective(curr):
941
+ curr = _next_curr
942
+ continue
943
+
944
+ if debug_num_collectives_to_reorder is not None and (
945
+ num_processed_collectives >= debug_num_collectives_to_reorder
946
+ ):
947
+ break
948
+ num_processed_collectives += 1
949
+
950
+ info = stats[curr] = ReorderInfo()
951
+ comm_time, comp_time, overlap_info = _coll_exposed_communication_time(
952
+ curr, _next, runtimes, node_output_sets, node_dep_sets
953
+ )
954
+ info.comm_time = comm_time
955
+ info.comp_time = comp_time
956
+ info.initial_exposed = info.final_exposed = comm_time - comp_time
957
+ info.overlap_info = overlap_info
958
+
959
+ candidate = _prev[curr]
960
+ group_head = curr
961
+ group_tail = curr
962
+ group_waits = {}
963
+ group_runtime = 0.0
964
+ group_peak_memory = _curr_memory[curr][0] # post_alloc memory
965
+
966
+ # Track group dependencies incrementally - initialize from pre-computed sets
967
+ group_unmet_deps_names = OrderedSet(node_dep_sets[curr])
968
+ group_output_names = OrderedSet(node_output_sets[curr])
969
+
970
+ while candidate is not None:
971
+ if config_comms.reorder_iterative_use_runtime_estimations and (
972
+ info.final_exposed
973
+ < -config_comms.reorder_iterative_extra_comm_comp_overlap
974
+ * info.comm_time
975
+ ):
976
+ info.limiting_factor = "unexposed by runtime estimations"
977
+ break
978
+
979
+ if (
980
+ not config_comms.reorder_iterative_unsafe_collectives_reorder
981
+ and contains_collective(candidate)
982
+ ):
983
+ info.limiting_factor = "collective ordering"
984
+ break
985
+
986
+ # Early exit: if group has no unmet dependencies, candidate can't have data dependency
987
+ data_deps_names = group_unmet_deps_names - group_output_names
988
+ if not data_deps_names:
989
+ data_dep = False
990
+ else:
991
+ # Calculate effective dependencies (not satisfied within group)
992
+ # Use pre-computed set for O(1) lookup
993
+ candidate_out_names = node_output_sets[candidate]
994
+ data_dep = bool(candidate_out_names & data_deps_names)
995
+
996
+ if data_dep:
997
+ is_groupable_result, grouping_reason = _is_node_groupable_for_reorder(
998
+ candidate
999
+ )
1000
+ if is_groupable_result:
1001
+ group_head = candidate
1002
+
1003
+ # Update incremental dependency tracking using pre-computed sets
1004
+ group_unmet_deps_names.update(node_dep_sets[candidate])
1005
+ group_output_names.update(node_output_sets[candidate])
1006
+
1007
+ if config_comms.reorder_iterative_use_runtime_estimations:
1008
+ if contains_wait(candidate):
1009
+ comm_time, comp_time, _ = _wait_exposed_communication_time(
1010
+ candidate,
1011
+ _head,
1012
+ _prev,
1013
+ runtimes,
1014
+ node_output_sets,
1015
+ node_dep_sets,
1016
+ )
1017
+ group_waits[candidate] = comm_time, comp_time
1018
+ if not contains_async_collective(candidate):
1019
+ group_runtime += runtimes[candidate]
1020
+
1021
+ group_peak_memory = max(
1022
+ group_peak_memory, _curr_memory[candidate][0]
1023
+ )
1024
+ info.grouped += 1
1025
+ candidate = _prev[candidate]
1026
+ continue
1027
+ else:
1028
+ msg = (
1029
+ f"data dependency detected"
1030
+ f"\n candidate:{candidate.get_name()}(outs:{[o.get_name() for o in candidate.get_outputs()]})"
1031
+ f"\n non_group_reason:{grouping_reason}"
1032
+ )
1033
+ info.limiting_factor = msg
1034
+ break
1035
+
1036
+ if config_comms.reorder_iterative_use_runtime_estimations:
1037
+ # Check if candidate has sync runtime
1038
+ if not contains_async_collective(candidate):
1039
+ c_runtime = runtimes[candidate]
1040
+
1041
+ if c_runtime > 0 and len(group_waits) > 0:
1042
+ # pyrefly: ignore[no-matching-overload]
1043
+ exposed_before = max(0, info.comm_time - info.comp_time)
1044
+ # pyrefly: ignore[no-matching-overload]
1045
+ exposed_after = max(
1046
+ 0, info.comm_time - info.comp_time - c_runtime
1047
+ )
1048
+ exposed_delta = exposed_after - exposed_before
1049
+ for gw_comm_time, gw_comp_time in group_waits.values():
1050
+ # pyrefly: ignore [no-matching-overload]
1051
+ gw_exposed_before = max(0, gw_comm_time - gw_comp_time)
1052
+ # pyrefly: ignore [no-matching-overload]
1053
+ gw_exposed_after = max(
1054
+ 0, gw_comm_time - gw_comp_time + c_runtime
1055
+ )
1056
+
1057
+ exposed_delta += gw_exposed_after - gw_exposed_before
1058
+
1059
+ if exposed_delta > 0:
1060
+ info.limiting_factor = (
1061
+ f"candidate has compute {c_runtime},"
1062
+ f" group contains waits, total_exposed_delta {exposed_delta}"
1063
+ )
1064
+ break
1065
+ else:
1066
+ # Update all group_colls comm_time, comp_time
1067
+ for gw, (
1068
+ gw_comm_time,
1069
+ gw_comp_time,
1070
+ ) in group_waits.items():
1071
+ group_waits[gw] = (
1072
+ gw_comm_time,
1073
+ gw_comp_time - c_runtime,
1074
+ )
1075
+ else:
1076
+ # Candidate is async_collective
1077
+
1078
+ # Unsafe collectives reordering
1079
+ # Cj -> [...group_runtime..., Ci] -> Wj
1080
+ # Checking that we are not increasing exposed time of Cj
1081
+ if group_runtime > 0:
1082
+ comm_time, comp_time, _ = _coll_exposed_communication_time(
1083
+ candidate, _next, runtimes, node_output_sets, node_dep_sets
1084
+ )
1085
+ # pyrefly: ignore[no-matching-overload]
1086
+ exposed_before = max(0, comm_time - comp_time)
1087
+ # pyrefly: ignore[no-matching-overload]
1088
+ exposed_after = max(0, comm_time - comp_time + group_runtime)
1089
+ exposed_delta = exposed_after - exposed_before
1090
+ if exposed_delta > 0:
1091
+ info.limiting_factor = (
1092
+ f"candidate {candidate.get_name()} is collective,"
1093
+ f" group_runtime:{group_runtime},"
1094
+ f" exposed_delta:{exposed_delta} c_comm_time:{comm_time} c_comp_time:{comp_time}"
1095
+ )
1096
+ break
1097
+
1098
+ # Create group nodes list once for swap operations
1099
+ gns: list[BaseSchedulerNode] = _group_nodes_from_linked_list(
1100
+ group_head, group_tail, _next
1101
+ )
1102
+
1103
+ candidate_allocfree: SNodeMemory = snodes_allocfree[candidate]
1104
+ candidate_delta_mem: int = (
1105
+ candidate_allocfree.size_alloc - candidate_allocfree.size_free
1106
+ )
1107
+ # candidate and one of group nodes are successors of the same buffer
1108
+ # and last use of the buffer happen in group nodes.
1109
+ # This last use deallocates it.
1110
+ # If we swap [candidate [group]] to [[group] candidate],
1111
+ # candidate becomes the last use
1112
+ # and deallocated this buffer instead of group node.
1113
+ # we need to update size_free accordingly to group_node and candidate,
1114
+ # and recalculate post_alloc, post_free for them.
1115
+ #
1116
+ # Buf that changes its last use snode,
1117
+ # after swap will be deallocated only by candidate,
1118
+ # while before it was deallocated by group node.
1119
+ group_n_to_bufs_after_swap_dealloc_by_candidate = (
1120
+ _find_buffers_with_changed_last_use(
1121
+ candidate, gns, buf_to_snode_last_use, candidate_buffer_map
1122
+ )
1123
+ )
1124
+
1125
+ potential_peak, _post_alloc_update = (
1126
+ _calculate_potential_peak_memory_reorder(
1127
+ candidate,
1128
+ gns,
1129
+ group_tail,
1130
+ group_peak_memory,
1131
+ candidate_delta_mem,
1132
+ candidate_allocfree,
1133
+ group_n_to_bufs_after_swap_dealloc_by_candidate,
1134
+ _curr_memory,
1135
+ )
1136
+ )
1137
+
1138
+ if (
1139
+ potential_peak - peak_memory
1140
+ > peak_memory * config_comms.reorder_iterative_peak_memory_budget
1141
+ ):
1142
+ info.limiting_factor = (
1143
+ f"peak memory new:{potential_peak} vs base:{peak_memory}"
1144
+ )
1145
+ break
1146
+ info.moves += 1
1147
+ total_moves += 1
1148
+
1149
+ _head = _perform_double_linked_list_swap(
1150
+ candidate, group_head, group_tail, _prev, _next, _head
1151
+ )
1152
+
1153
+ comm_time, comp_time, overlap_info = _coll_exposed_communication_time(
1154
+ curr, _next, runtimes, node_output_sets, node_dep_sets
1155
+ )
1156
+ info.comm_time = comm_time
1157
+ info.comp_time = comp_time
1158
+ info.overlap_info = overlap_info
1159
+ info.final_exposed = comm_time - comp_time
1160
+
1161
+ _update_memory_tracking_after_swap_reorder(
1162
+ candidate,
1163
+ gns,
1164
+ group_tail,
1165
+ candidate_delta_mem,
1166
+ candidate_allocfree,
1167
+ group_n_to_bufs_after_swap_dealloc_by_candidate,
1168
+ _post_alloc_update,
1169
+ _curr_memory,
1170
+ buf_to_snode_last_use,
1171
+ snodes_allocfree,
1172
+ )
1173
+
1174
+ if debug_iterative_memory_recompute:
1175
+ # Compare iteratively recomputed memory data
1176
+ # with full run of estimate_peak_memory
1177
+
1178
+ from .comms_debug import _debug_iterative_memory_recompute
1179
+
1180
+ iterative_recompute_error = _debug_iterative_memory_recompute(
1181
+ candidate,
1182
+ gns,
1183
+ _group_names(gns),
1184
+ _group_nodes_from_linked_list(_head, None, _next),
1185
+ name_to_freeable_input_buf,
1186
+ graph_outputs,
1187
+ peak_memory,
1188
+ _curr_memory,
1189
+ snodes_allocfree,
1190
+ "reorder_communication_preserving_peak_memory",
1191
+ group_n_to_bufs_after_swap_dealloc_by_candidate,
1192
+ )
1193
+ if iterative_recompute_error:
1194
+ break
1195
+ candidate = _prev[group_head]
1196
+ curr = _next_curr
1197
+
1198
+ if not config_comms.reorder_sink_verbose_logging:
1199
+ new_snodes = _group_nodes_from_linked_list(_head, None, _next)
1200
+ return new_snodes, stats
1201
+
1202
+ new_snodes = _format_and_log_reordering_stats(
1203
+ stats,
1204
+ _head,
1205
+ _next,
1206
+ original_snodes_num,
1207
+ peak_memory,
1208
+ name_to_freeable_input_buf,
1209
+ graph_outputs,
1210
+ )
1211
+
1212
+ return new_snodes, stats
1213
+
1214
+
1215
+ def _schedule_for_comm(
1216
+ snodes: list[BaseSchedulerNode],
1217
+ raise_comms: bool,
1218
+ sink_waits: bool,
1219
+ reorder_for_overlap: bool,
1220
+ ) -> list[BaseSchedulerNode]:
1221
+ """
1222
+ Schedule `snodes` for various comm optimization objectives.
1223
+
1224
+ Args:
1225
+ snodes: the nodes to be scheduled.
1226
+ raise_comms: whether to greedily schedule collectives as early as possible
1227
+ sink_wait: whether to greedily schedule waits as late as possible
1228
+ reorder_compute_for_overlap: whether to reorder compute nodes to
1229
+ optimize for compute/communication overlapping.
1230
+
1231
+ Returns:
1232
+ The new schedule order.
1233
+
1234
+ Some notes on the synergy between different options:
1235
+ - `raise_comms` provides more overlapping opportunities for `reorder_compute_for_overlap`.
1236
+ - When both `raise_comms` and `sink_waits` is `True`, `raise_comms` is prioritized.
1237
+ """
1238
+ # We assign each node a tuple of scores (score_0, score_1, score_2),
1239
+ # decreasing in importance, with a lower value indicating a higher ranking:
1240
+ #
1241
+ # - score_0: the lowest comm_idx among the comm nodes that the node blocks.
1242
+ # If a node doesn't block any comm nodes, its score_0 is set to
1243
+ # sys.maxsize. This score ensures that comm nodes get scheduled as early as
1244
+ # possible.
1245
+ # - score_1: 1 if the node is a wait node, 0 otherwise. This score ensures
1246
+ # that wait nodes are deferred as late as possible.
1247
+ # - score_2: the index of the node in the original topological order. This
1248
+ # score provides stability in case of ties.
1249
+ #
1250
+ # When only raise_comms is True, only score_0 and score_2 are considered.
1251
+ # When only sink_waits is True, only score_1 and score_2 are considered.
1252
+ # When neither is True, the original order is yielded.
1253
+ buf_name_to_snode = {}
1254
+ name_to_fused_node = {}
1255
+ scores_0, scores_1, scores_2 = {}, {}, {}
1256
+ for idx, snode in enumerate(snodes):
1257
+ for buf_name in snode.get_buffer_names():
1258
+ buf_name_to_snode[buf_name] = snode
1259
+
1260
+ for op_name in snode.get_operation_names():
1261
+ name_to_fused_node[op_name] = snode
1262
+ name_to_fused_node[snode.get_name()] = snode
1263
+
1264
+ node_name = snode.get_name()
1265
+ scores_0[node_name] = sys.maxsize
1266
+ scores_1[node_name] = 0
1267
+ scores_2[node_name] = idx
1268
+
1269
+ comm_idx = 0
1270
+ for snode in snodes:
1271
+ if raise_comms and contains_collective(snode):
1272
+ scores_0[snode.get_name()] = comm_idx
1273
+ for ancestor in snode.ancestors:
1274
+ anc_fused_name = name_to_fused_node[ancestor].get_name()
1275
+ scores_0[anc_fused_name] = min(scores_0[anc_fused_name], comm_idx)
1276
+ comm_idx += 1
1277
+ elif sink_waits and contains_wait(snode):
1278
+ scores_1[snode.get_name()] = 1
1279
+
1280
+ class Runnable:
1281
+ def __init__(self, snode) -> None:
1282
+ self.snode = snode
1283
+ name = next(iter(snode.get_operation_names()))
1284
+ fused_name = name_to_fused_node[name].get_name()
1285
+ self.score = (
1286
+ scores_0[fused_name],
1287
+ scores_1[fused_name],
1288
+ scores_2[fused_name],
1289
+ )
1290
+
1291
+ def __lt__(self, other):
1292
+ return self.score < other.score
1293
+
1294
+ unmet_deps: dict[BaseSchedulerNode, OrderedSet[str]] = {
1295
+ snode: OrderedSet(dep.name for dep in snode.unmet_dependencies)
1296
+ for snode in snodes
1297
+ }
1298
+
1299
+ ready: list[Runnable] = []
1300
+ buffer_users: dict[str, OrderedSet[BaseSchedulerNode]] = defaultdict(OrderedSet)
1301
+ snode_to_cost = {snode: estimate_op_runtime(snode) for snode in snodes}
1302
+
1303
+ for snode, deps in unmet_deps.items():
1304
+ if len(deps) == 0:
1305
+ heapq.heappush(ready, Runnable(snode))
1306
+ for dep in deps:
1307
+ buffer_users[dep].add(snode)
1308
+
1309
+ scheduled = []
1310
+
1311
+ def schedule(snode):
1312
+ """
1313
+ Schedules `snode` and put all unblocked nodes onto the ready queue.
1314
+ """
1315
+ scheduled.append(snode)
1316
+ for buf_name in snode.get_buffer_names():
1317
+ for snode in buffer_users[buf_name]:
1318
+ unmet_deps[snode].remove(buf_name)
1319
+ if len(unmet_deps[snode]) == 0:
1320
+ heapq.heappush(ready, Runnable(snode))
1321
+
1322
+ def get_overlapping_candidate():
1323
+ """
1324
+ Return the next node in the ready queue that's neither a collective or
1325
+ a wait.
1326
+ """
1327
+ candidates = [
1328
+ x
1329
+ for x in ready
1330
+ if not contains_collective(x.snode) and not contains_wait(x.snode)
1331
+ ]
1332
+ if len(candidates) == 0:
1333
+ return None
1334
+ return min(candidates, key=lambda x: x.score)
1335
+
1336
+ def schedule_collective_for_overlap(snode):
1337
+ """
1338
+ Schedules collective node `snode`, along with one or more compute nodes
1339
+ to overlap with it. The strategy is described in the comment of
1340
+ `reorder_compute_for_overlap`.
1341
+ """
1342
+ if not contains_collective(snode):
1343
+ raise AssertionError("expected snode to contain a collective")
1344
+ schedule(snode)
1345
+
1346
+ collective_cost = snode_to_cost[snode]
1347
+ while (
1348
+ collective_cost > 0
1349
+ and (candidate := get_overlapping_candidate()) is not None
1350
+ ):
1351
+ ready.remove(candidate)
1352
+
1353
+ schedule(candidate.snode)
1354
+
1355
+ collective_cost -= snode_to_cost[candidate.snode]
1356
+ heapq.heapify(ready)
1357
+
1358
+ while ready:
1359
+ snode = heapq.heappop(ready).snode
1360
+ if reorder_for_overlap and contains_collective(snode):
1361
+ schedule_collective_for_overlap(snode)
1362
+ else:
1363
+ schedule(snode)
1364
+
1365
+ for deps in unmet_deps.values():
1366
+ if len(deps) != 0:
1367
+ raise AssertionError(
1368
+ f"Detected unscheduled nodes. Nodes with unmet dependencies: {unmet_deps}"
1369
+ )
1370
+ return scheduled
1371
+
1372
+
1373
+ def decide_global_ordering_of_comms(
1374
+ nodes: list[BaseSchedulerNode], name_to_buf, name_to_fused_node
1375
+ ) -> list[BaseSchedulerNode]:
1376
+ """
1377
+ Decide global ordering of comms, by just enforcing the ordering that's in the input graph
1378
+ (might not be the same ordering as the eager mode program).
1379
+ TODO: Come up with a better approach
1380
+ """
1381
+ if not torch.distributed.is_available():
1382
+ return nodes
1383
+
1384
+ comm_nodes = [n for n in nodes if contains_collective(n)]
1385
+
1386
+ for i in range(1, len(comm_nodes)):
1387
+ # Enforce ordering by making previous comm a `WeakDep` dependency of the next comm
1388
+ mutating_buf = next(iter(comm_nodes[i].get_buffer_names()))
1389
+ for buf in comm_nodes[i - 1].get_buffer_names():
1390
+ comm_nodes[i].add_fake_dep(
1391
+ WeakDep(buf, mutating_buf=mutating_buf, is_fake=True)
1392
+ )
1393
+
1394
+ return nodes
1395
+
1396
+
1397
+ @dataclass
1398
+ class SinkWaitInfo:
1399
+ grouped: int = 0
1400
+ grouped_info: str = ""
1401
+ moves: int = 0
1402
+ moves_info: str = ""
1403
+ limiting_factor: str = "None"
1404
+ comm_time: float = -1.0
1405
+ comp_time: float = -1.0
1406
+ initial_exposed: float = -1.0
1407
+ final_exposed: float = -1.0
1408
+ overlap_info: str = "None"
1409
+
1410
+ @property
1411
+ def improvement(self):
1412
+ return self.initial_exposed - self.final_exposed
1413
+
1414
+
1415
+ def _is_node_groupable_for_sink_waits(
1416
+ candidate: BaseSchedulerNode,
1417
+ ) -> tuple[bool, str | None]:
1418
+ """
1419
+ Check if a candidate node can be grouped during sink_waits pass.
1420
+
1421
+ Sink Waits traverses waits right to left, so we don't group with
1422
+ processed waits on the right or with async collectives.
1423
+
1424
+ Args:
1425
+ candidate: Node to check for groupability
1426
+
1427
+ Returns:
1428
+ Tuple of (is_groupable, reason_if_not_groupable)
1429
+ """
1430
+ # Sink Waits traverse Waits right to left,
1431
+ # => we do not group with processed Waits on the right.
1432
+ if contains_wait(candidate):
1433
+ return False, f"candidate contains wait {candidate.get_name()}"
1434
+ if contains_async_collective(candidate):
1435
+ return (
1436
+ False,
1437
+ f"candidate contains_async_collective {candidate.get_name()}",
1438
+ )
1439
+
1440
+ if not config_comms.sink_iterative_use_runtime_estimations:
1441
+ # Heuristics pre-use_runtime_estimations:
1442
+ # TODO(ivankobzarev): Remove them after confirming,
1443
+ # that using runtime estimations always give better results.
1444
+ # We do not want to group with collectives to not reorder them forward.
1445
+ if contains_collective(candidate):
1446
+ return (
1447
+ False,
1448
+ f"candidate contains collective {candidate.get_name()}",
1449
+ )
1450
+ if contains_gemm_like(candidate):
1451
+ return (
1452
+ False,
1453
+ f"candidate contains gemm_like {candidate.get_name()}",
1454
+ )
1455
+ return True, None
1456
+
1457
+
1458
+ def _update_memory_tracking_after_swap_sink_waits(
1459
+ candidate: BaseSchedulerNode,
1460
+ gns: list[BaseSchedulerNode],
1461
+ candidate_delta_mem: int,
1462
+ candidate_allocfree: SNodeMemory,
1463
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict,
1464
+ post_alloc_update: dict[BaseSchedulerNode, int],
1465
+ size_free_delta_update: dict[BaseSchedulerNode, int],
1466
+ curr_memory: dict,
1467
+ snodes_allocfree: dict,
1468
+ ) -> None:
1469
+ """
1470
+ Update memory tracking structures after swap (sink_waits version).
1471
+
1472
+ Updates curr_memory and snodes_allocfree dictionaries to reflect the new
1473
+ memory state after swapping candidate with group.
1474
+
1475
+ Args:
1476
+ candidate: Node that was moved
1477
+ gns: Group nodes
1478
+ candidate_delta_mem: Net memory change from candidate (alloc - free)
1479
+ candidate_allocfree: Candidate's allocation/free info
1480
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group
1481
+ post_alloc_update: Cached post-allocation memory values
1482
+ size_free_delta_update: Cached size-free delta values
1483
+ curr_memory: Current memory state dict (mutated)
1484
+ snodes_allocfree: Node allocation/free info dict (mutated)
1485
+ """
1486
+ group_head = gns[0]
1487
+ pre_group_mem = curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc
1488
+ if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
1489
+ candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc
1490
+ curr_memory[candidate] = (
1491
+ candidate_post_alloc,
1492
+ candidate_post_alloc - candidate_allocfree.size_free,
1493
+ )
1494
+ for gn in gns:
1495
+ cm = curr_memory[gn]
1496
+ curr_memory[gn] = (
1497
+ cm[0] + candidate_delta_mem,
1498
+ cm[1] + candidate_delta_mem,
1499
+ )
1500
+ return
1501
+
1502
+ for n in [candidate, *gns]:
1503
+ post_alloc = post_alloc_update[n]
1504
+ snodes_allocfree[n].size_free += size_free_delta_update.get(n, 0)
1505
+ curr_memory[n] = (
1506
+ post_alloc,
1507
+ post_alloc - snodes_allocfree[n].size_free,
1508
+ )
1509
+
1510
+
1511
+ def _calculate_potential_peak_memory_sink_waits(
1512
+ candidate: BaseSchedulerNode,
1513
+ gns: list[BaseSchedulerNode],
1514
+ group_head: BaseSchedulerNode,
1515
+ group_peak_memory: int,
1516
+ candidate_delta_mem: int,
1517
+ candidate_allocfree: SNodeMemory,
1518
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict,
1519
+ curr_memory: dict,
1520
+ snodes_allocfree: dict,
1521
+ ) -> tuple[int, dict[BaseSchedulerNode, int], dict[BaseSchedulerNode, int]]:
1522
+ """
1523
+ Calculate potential peak memory after swapping candidate with group (sink_waits version).
1524
+
1525
+ Computes new memory levels for all affected nodes and returns the potential
1526
+ peak memory along with cached post-allocation and size-free delta values.
1527
+
1528
+ Args:
1529
+ candidate: Node being moved
1530
+ gns: Group nodes
1531
+ group_head: First node of group
1532
+ group_peak_memory: Current peak memory within the group
1533
+ candidate_delta_mem: Net memory change from candidate (alloc - free)
1534
+ candidate_allocfree: Candidate's allocation/free info
1535
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate: Buffers whose deallocation moves from candidate to group
1536
+ curr_memory: Current memory state dict
1537
+ snodes_allocfree: Allocation/free info for all nodes
1538
+
1539
+ Returns:
1540
+ Tuple of (potential_peak_memory, post_alloc_update_dict, size_free_delta_update_dict)
1541
+ """
1542
+ pre_group_mem = curr_memory[group_head][0] - snodes_allocfree[group_head].size_alloc
1543
+ # Stash memory tracing updates to not recompute them after swap
1544
+ _post_alloc_update: dict[BaseSchedulerNode, int] = {}
1545
+ _size_free_delta_update: dict[BaseSchedulerNode, int] = {}
1546
+
1547
+ potential_peak = 0
1548
+ if not group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
1549
+ # Not accounting for buffers liveliness change
1550
+ potential_peak = max(
1551
+ group_peak_memory + candidate_delta_mem,
1552
+ pre_group_mem + candidate_allocfree.size_alloc,
1553
+ )
1554
+ return potential_peak, _post_alloc_update, _size_free_delta_update
1555
+
1556
+ candidate_post_alloc = pre_group_mem + candidate_allocfree.size_alloc
1557
+ _post_alloc_update[candidate] = candidate_post_alloc
1558
+ potential_peak = candidate_post_alloc
1559
+ candidate_size_free_to_move = sum(
1560
+ buf.mpi_buffer.size_free # type: ignore[attr-defined]
1561
+ for buf in itertools.chain.from_iterable(
1562
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate.values()
1563
+ )
1564
+ )
1565
+ _size_free_delta_update[candidate] = -candidate_size_free_to_move
1566
+ delta_mem = candidate_delta_mem + candidate_size_free_to_move
1567
+ for gn in gns:
1568
+ gn_post_alloc = curr_memory[gn][0] + delta_mem
1569
+ _post_alloc_update[gn] = gn_post_alloc
1570
+ potential_peak = max(potential_peak, gn_post_alloc)
1571
+ gn_size_free_to_add = 0
1572
+ if gn in group_n_to_bufs_after_swap_dealloc_instead_of_candidate:
1573
+ bufs = group_n_to_bufs_after_swap_dealloc_instead_of_candidate[gn]
1574
+ for buf in bufs:
1575
+ gn_size_free_to_add += buf.mpi_buffer.size_free
1576
+ _size_free_delta_update[gn] = gn_size_free_to_add
1577
+ delta_mem -= gn_size_free_to_add
1578
+ return potential_peak, _post_alloc_update, _size_free_delta_update
1579
+
1580
+
1581
+ def _perform_double_linked_list_swap_sink_waits(
1582
+ candidate: BaseSchedulerNode,
1583
+ group_head: BaseSchedulerNode,
1584
+ group_tail: BaseSchedulerNode,
1585
+ prev_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
1586
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
1587
+ head: BaseSchedulerNode,
1588
+ ) -> BaseSchedulerNode:
1589
+ """
1590
+ Swap positions of candidate and group in doubly-linked list (sink_waits version).
1591
+
1592
+ Transforms (moves candidate to the left):
1593
+ group_head_prev -> group_head...group_tail -> candidate -> candidate_next
1594
+ Into:
1595
+ group_head_prev -> candidate -> group_head...group_tail -> candidate_next
1596
+
1597
+ Args:
1598
+ candidate: Node to swap with group
1599
+ group_head: First node of group
1600
+ group_tail: Last node of group
1601
+ prev_dict: Dictionary mapping nodes to their previous nodes
1602
+ next_dict: Dictionary mapping nodes to their next nodes
1603
+ head: Current head of the linked list
1604
+
1605
+ Returns:
1606
+ New head of the linked list (may change if group_head was the head)
1607
+ """
1608
+ # 0: Update group_head's previous node
1609
+ group_head_prev = prev_dict[group_head]
1610
+ if group_head_prev:
1611
+ next_dict[group_head_prev] = candidate
1612
+ prev_dict[candidate] = group_head_prev
1613
+
1614
+ # 2: Update candidate's next node
1615
+ candidate_next = next_dict[candidate]
1616
+ if candidate_next:
1617
+ prev_dict[candidate_next] = group_tail
1618
+ next_dict[group_tail] = candidate_next
1619
+
1620
+ # 1: Link candidate to group_head
1621
+ prev_dict[group_head] = candidate
1622
+ next_dict[candidate] = group_head
1623
+
1624
+ # Update head if group_head was the head
1625
+ if group_head == head:
1626
+ return candidate
1627
+ return head
1628
+
1629
+
1630
+ def _format_and_log_sink_waits_stats(
1631
+ stats: dict[BaseSchedulerNode, SinkWaitInfo],
1632
+ head: BaseSchedulerNode,
1633
+ next_dict: dict[BaseSchedulerNode, BaseSchedulerNode | None],
1634
+ original_snodes_num: int,
1635
+ peak_memory: int,
1636
+ name_to_freeable_input_buf: dict,
1637
+ graph_outputs: OrderedSet[str],
1638
+ ) -> list[BaseSchedulerNode]:
1639
+ """
1640
+ Format sink_waits statistics, log them, and return final node list.
1641
+
1642
+ Computes improvement metrics, creates a formatted table (using tabulate if
1643
+ available), validates the reordered node count, recalculates peak memory,
1644
+ and logs all information.
1645
+
1646
+ Args:
1647
+ stats: Per-node sink_waits statistics
1648
+ head: Head of the reordered linked list
1649
+ next_dict: Linked list next pointers
1650
+ original_snodes_num: Original number of nodes (for validation)
1651
+ peak_memory: Initial peak memory before reordering
1652
+ name_to_freeable_input_buf: Buffer memory tracking info
1653
+ graph_outputs: Graph output names
1654
+
1655
+ Returns:
1656
+ Final reordered list of scheduler nodes
1657
+ """
1658
+ headers = [
1659
+ "Wait node",
1660
+ "comm_time(us)",
1661
+ "comp_time(us)",
1662
+ "initial exposed(us)",
1663
+ "final exposed(us)",
1664
+ "improvement(us)",
1665
+ "limiting factor",
1666
+ "grouped",
1667
+ "grouped_info",
1668
+ "moves",
1669
+ "moves_info",
1670
+ "overlap_info",
1671
+ ]
1672
+ rows = [
1673
+ [
1674
+ node_summary(snode),
1675
+ info.comm_time / 1e3,
1676
+ info.comp_time / 1e3,
1677
+ info.initial_exposed / 1e3,
1678
+ info.final_exposed / 1e3,
1679
+ info.improvement / 1e3,
1680
+ info.limiting_factor,
1681
+ info.grouped,
1682
+ info.grouped_info,
1683
+ info.moves,
1684
+ info.moves_info,
1685
+ info.overlap_info,
1686
+ ]
1687
+ for snode, info in stats.items()
1688
+ ]
1689
+ log_str = ""
1690
+ if importlib.util.find_spec("tabulate"):
1691
+ from tabulate import tabulate
1692
+
1693
+ log_str += tabulate(
1694
+ rows,
1695
+ headers=headers,
1696
+ )
1697
+ else:
1698
+ log_str += "Please `pip install tabulate` to nicely render overlap stats.\n"
1699
+ log_str += str(headers) + "\n"
1700
+ log_str += "\n".join(map(str, rows))
1701
+ overlap_log.info(log_str)
1702
+ new_snodes = _group_nodes_from_linked_list(head, None, next_dict)
1703
+ if len(new_snodes) != original_snodes_num:
1704
+ raise AssertionError(
1705
+ f"expected {original_snodes_num} nodes, got {len(new_snodes)}"
1706
+ )
1707
+ new_peak_memory, _, _, _ = estimate_peak_memory_allocfree(
1708
+ new_snodes, name_to_freeable_input_buf, graph_outputs
1709
+ )
1710
+ log_str += f"\n sink_waits_iterative peak_memory_before:{peak_memory}"
1711
+ log_str += f"\n sink_waits_iterative peak_memory_after:{new_peak_memory}"
1712
+ trace_structured(
1713
+ "artifact",
1714
+ metadata_fn=lambda: {
1715
+ "name": "sink_waits_iterative_info",
1716
+ "encoding": "string",
1717
+ },
1718
+ payload_fn=lambda: log_str,
1719
+ )
1720
+ return new_snodes
1721
+
1722
+
1723
+ def _find_buffers_with_changed_last_use_sink_waits(
1724
+ candidate: BaseSchedulerNode,
1725
+ gns: list[BaseSchedulerNode],
1726
+ buf_to_snode_last_use: dict,
1727
+ candidate_buffer_map: dict[BaseSchedulerNode, OrderedSet],
1728
+ ) -> dict[BaseSchedulerNode, list[FreeableInputBuffer | Any]]:
1729
+ """
1730
+ Find buffers whose last use will change after swapping in sink_waits pass.
1731
+
1732
+ When we swap [group] candidate to candidate [group], some buffers that
1733
+ were last used by candidate will now be last used by a group node instead.
1734
+ This is the opposite direction from the reorder version.
1735
+
1736
+ Args:
1737
+ candidate: The node being moved (currently last use)
1738
+ gns: Group nodes being swapped with candidate
1739
+ buf_to_snode_last_use: Mapping of buffers to their current last-use nodes
1740
+ candidate_buffer_map: Pre-computed map of node -> buffers using that node
1741
+
1742
+ Returns:
1743
+ Dict mapping group nodes to buffers that will change their last-use node
1744
+ """
1745
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate: dict[
1746
+ BaseSchedulerNode, list[FreeableInputBuffer | Any]
1747
+ ] = defaultdict(list)
1748
+
1749
+ # Optimization: only check buffers where candidate is a successor
1750
+ # Reduces from O(all_buffers) to O(buffers_per_candidate)
1751
+ candidate_bufs = candidate_buffer_map.get(candidate, OrderedSet())
1752
+
1753
+ for buf in candidate_bufs:
1754
+ snode_last_use = buf_to_snode_last_use[buf]
1755
+ if snode_last_use != candidate:
1756
+ continue
1757
+
1758
+ # candidate is last use of buf
1759
+ # Find last group node in successors (maintains order)
1760
+ succ_nodes = buf.mpi_buffer.succ_nodes
1761
+ last_succ_gn = None
1762
+ for gn in gns:
1763
+ if gn in succ_nodes:
1764
+ last_succ_gn = gn
1765
+
1766
+ if last_succ_gn is None:
1767
+ continue
1768
+
1769
+ # gn has successors of buf that after potential swap will become
1770
+ # last use of buf and start deallocating buf instead of candidate
1771
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate[last_succ_gn].append(
1772
+ buf
1773
+ )
1774
+
1775
+ return group_n_to_bufs_after_swap_dealloc_instead_of_candidate
1776
+
1777
+
1778
+ def _sink_waits_iterative_internal(
1779
+ snodes: list[BaseSchedulerNode],
1780
+ ) -> tuple[list[BaseSchedulerNode], dict[BaseSchedulerNode, SinkWaitInfo]]:
1781
+ original_snodes_num = len(snodes)
1782
+ if original_snodes_num == 0:
1783
+ return snodes, {}
1784
+ graph_inputs: OrderedSet[str] = OrderedSet(V.graph.graph_inputs.keys())
1785
+ graph_outputs: OrderedSet[str] = OrderedSet(V.graph.get_output_names())
1786
+ (
1787
+ peak_memory,
1788
+ _curr_memory,
1789
+ snodes_allocfree,
1790
+ buf_to_snode_last_use,
1791
+ name_to_freeable_input_buf,
1792
+ candidate_buffer_map,
1793
+ ) = _initialize_memory_tracking(snodes, graph_inputs, graph_outputs)
1794
+
1795
+ _prev, _next, _head = _initialize_double_linked_list(snodes)
1796
+
1797
+ stats: dict[BaseSchedulerNode, SinkWaitInfo] = {}
1798
+
1799
+ runtimes: dict[BaseSchedulerNode, float] = {
1800
+ snode: estimate_op_runtime(snode) * _op_runtime_estimate_mult(snode)
1801
+ for snode in snodes
1802
+ }
1803
+
1804
+ # Pre-compute output and dependency sets for O(1) lookup instead of O(N) creation per iteration
1805
+ node_output_sets: dict[BaseSchedulerNode, frozenset[str]] = {
1806
+ snode: frozenset(o.get_name() for o in snode.get_outputs()) for snode in snodes
1807
+ }
1808
+ node_dep_sets: dict[BaseSchedulerNode, frozenset[str]] = {
1809
+ snode: frozenset(
1810
+ d.name for d in snode.unmet_dependencies if not _is_fake_dep(d)
1811
+ )
1812
+ for snode in snodes
1813
+ }
1814
+
1815
+ curr: BaseSchedulerNode | None = snodes[-1]
1816
+
1817
+ processed_waits = OrderedSet() # type: ignore[var-annotated]
1818
+ debug_iterative_memory_recompute = (
1819
+ config_comms.reorder_iterative_debug_memory_recompute
1820
+ )
1821
+ debug_num_sink_waits_to_reorder: int | None = (
1822
+ config_comms.sink_waits_iterative_debug_limit_to_sink
1823
+ )
1824
+
1825
+ iterative_recompute_error = False
1826
+ while curr is not None and _prev[curr] is not None:
1827
+ _prev_curr = _prev[curr]
1828
+ if iterative_recompute_error:
1829
+ break
1830
+ if (
1831
+ debug_num_sink_waits_to_reorder is not None
1832
+ and len(processed_waits) >= debug_num_sink_waits_to_reorder
1833
+ ):
1834
+ break
1835
+
1836
+ if not (contains_wait(curr) and curr not in processed_waits):
1837
+ curr = _prev_curr
1838
+ continue
1839
+
1840
+ processed_waits.add(curr)
1841
+ info = stats[curr] = SinkWaitInfo()
1842
+ comm_time, comp_time, overlap_info = _wait_exposed_communication_time(
1843
+ curr, _head, _prev, runtimes, node_output_sets, node_dep_sets
1844
+ )
1845
+ info.initial_exposed = info.final_exposed = comm_time - comp_time
1846
+ info.comm_time = comm_time
1847
+ info.comp_time = comp_time
1848
+ info.overlap_info = overlap_info
1849
+
1850
+ candidate = _next[curr]
1851
+ group_head = curr
1852
+ group_tail = curr
1853
+ group_colls = {}
1854
+ group_runtime = 0.0
1855
+ group_peak_memory = _curr_memory[curr][0]
1856
+
1857
+ # Track group outputs and check collective status incrementally - initialize from pre-computed set
1858
+ group_output_names = OrderedSet(node_output_sets[curr])
1859
+ group_contains_collective = contains_collective(curr)
1860
+
1861
+ while candidate is not None:
1862
+ if config_comms.sink_iterative_use_runtime_estimations and (
1863
+ info.final_exposed
1864
+ < -config_comms.sink_iterative_extra_comm_comp_overlap * info.comm_time
1865
+ ):
1866
+ info.limiting_factor = "unexposed by runtime estimations"
1867
+ break
1868
+
1869
+ # Early exit: if group has no outputs, candidate can't depend on it
1870
+ if not group_output_names:
1871
+ data_dep = False
1872
+ else:
1873
+ # Calculate candidate dependencies using pre-computed set
1874
+ candidate_dep_names = node_dep_sets[candidate]
1875
+ data_dep = bool(candidate_dep_names & group_output_names)
1876
+
1877
+ # Conservative sink wait, limiting by space before next collective.
1878
+ # The global strategy is that bucketing should create space.
1879
+ # For 2D we can experiment with allowing to sink Wait beyond non current group collective.
1880
+
1881
+ if not config_comms.sink_waits_iterative_swap_with_collectives:
1882
+ if contains_async_collective(candidate):
1883
+ info.limiting_factor = (
1884
+ f"candidate contains_async_collective {candidate.get_name()}"
1885
+ )
1886
+ break
1887
+
1888
+ # 1. If we have data_dep - we can not swap => trying to group
1889
+ # 2. If swap candidate and current node both contain collectives => trying to group
1890
+ both_contain_comms = group_contains_collective and contains_collective(
1891
+ candidate
1892
+ )
1893
+ if data_dep or both_contain_comms:
1894
+ _is_groupable, groupable_reason = _is_node_groupable_for_sink_waits(
1895
+ candidate
1896
+ )
1897
+ if _is_groupable:
1898
+ group_tail = candidate
1899
+
1900
+ # Update incremental tracking using pre-computed set
1901
+ group_output_names.update(node_output_sets[candidate])
1902
+ group_contains_collective = (
1903
+ group_contains_collective or contains_collective(candidate)
1904
+ )
1905
+
1906
+ if (
1907
+ config_comms.sink_iterative_use_runtime_estimations
1908
+ and contains_collective(candidate)
1909
+ ):
1910
+ comm_time, comp_time, _ = _coll_exposed_communication_time(
1911
+ candidate, _next, runtimes, node_output_sets, node_dep_sets
1912
+ )
1913
+ group_colls[candidate] = (comm_time, comp_time)
1914
+ if not contains_async_collective(candidate):
1915
+ group_runtime += runtimes[candidate]
1916
+
1917
+ group_peak_memory = max(
1918
+ group_peak_memory, _curr_memory[candidate][0]
1919
+ )
1920
+ info.grouped += 1
1921
+ candidate = _next[candidate]
1922
+ continue
1923
+ elif not data_dep:
1924
+ if (
1925
+ not config_comms.sink_waits_iterative_unsafe_collectives_reorder
1926
+ and both_contain_comms
1927
+ ):
1928
+ info.limiting_factor = (
1929
+ f"collective ordering"
1930
+ f"\n with candidate:{candidate.get_name()}"
1931
+ )
1932
+ break
1933
+ else:
1934
+ info.limiting_factor = (
1935
+ f"data dependency detected"
1936
+ f"\n candidate:{candidate.get_name()}"
1937
+ f"\n non_group_reason:{groupable_reason}"
1938
+ )
1939
+ break
1940
+
1941
+ if config_comms.sink_iterative_use_runtime_estimations:
1942
+ if is_wait(candidate.node):
1943
+ # Corresponding collective is before the group,
1944
+ # Swap can increase exposed time of corresponding collective
1945
+ comm_time, comp_time, _ = _wait_exposed_communication_time(
1946
+ candidate,
1947
+ _head,
1948
+ _prev,
1949
+ runtimes,
1950
+ node_output_sets,
1951
+ node_dep_sets,
1952
+ )
1953
+ # pyrefly: ignore[no-matching-overload]
1954
+ exposed_before = max(0, comm_time - comp_time)
1955
+ # pyrefly: ignore[no-matching-overload]
1956
+ exposed_after = max(0, comm_time - comp_time + group_runtime)
1957
+ # We do not know how much we can sink more after this swap,
1958
+ # Just comparing advantage at the moment for now.
1959
+ if exposed_after > exposed_before:
1960
+ info.limiting_factor = (
1961
+ "candidate is wait,"
1962
+ f" exposed_before:{exposed_before} vs exposed_after:{exposed_after}"
1963
+ )
1964
+ break
1965
+
1966
+ # Check if candidate has sync runtime
1967
+ if not contains_async_collective(candidate):
1968
+ # If candidate has sync runtime,
1969
+ # Waits of gorup_colls are on the right from group.
1970
+ # Swap can increase their exposed time.
1971
+ c_runtime = runtimes[candidate]
1972
+
1973
+ if c_runtime > 0 and len(group_colls) > 0:
1974
+ # pyrefly: ignore[no-matching-overload]
1975
+ exposed_before = max(0, info.comm_time - info.comp_time)
1976
+ # pyrefly: ignore[no-matching-overload]
1977
+ exposed_after = max(
1978
+ 0, info.comm_time - info.comp_time - c_runtime
1979
+ )
1980
+ exposed_delta = exposed_after - exposed_before
1981
+ for gc_comm_time, gc_comp_time in group_colls.values():
1982
+ # pyrefly: ignore [no-matching-overload]
1983
+ gc_exposed_before = max(0, gc_comm_time - gc_comp_time)
1984
+ # pyrefly: ignore [no-matching-overload]
1985
+ gc_exposed_after = max(
1986
+ 0, gc_comm_time - gc_comp_time + c_runtime
1987
+ )
1988
+ exposed_delta += gc_exposed_after - gc_exposed_before
1989
+ if exposed_delta > 0:
1990
+ info.limiting_factor = (
1991
+ f"candidate has compute {c_runtime}, group contains collectives,"
1992
+ f" total_exposed_delta {exposed_delta}"
1993
+ )
1994
+ break
1995
+ else:
1996
+ # Update all group_colls comm_time, comp_time
1997
+ for gc, (
1998
+ gc_comm_time,
1999
+ gc_comp_time,
2000
+ ) in group_colls.items():
2001
+ group_colls[gc] = (
2002
+ gc_comm_time,
2003
+ gc_comp_time - c_runtime,
2004
+ )
2005
+
2006
+ # Create group nodes list once for swap operations
2007
+ gns: list[BaseSchedulerNode] = _group_nodes_from_linked_list(
2008
+ group_head, group_tail, _next
2009
+ )
2010
+
2011
+ candidate_allocfree: SNodeMemory = snodes_allocfree[candidate]
2012
+ candidate_delta_mem = (
2013
+ candidate_allocfree.size_alloc - candidate_allocfree.size_free
2014
+ )
2015
+ # [group] candidate -> candidate [group]
2016
+ # Check for buffers with successors in group and candidate last successor
2017
+ #
2018
+ # Buf that changes its last use snode,
2019
+ # It was deallocated by candidate,
2020
+ # but after swap it will be deallocated by group node.
2021
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate = (
2022
+ _find_buffers_with_changed_last_use_sink_waits(
2023
+ candidate, gns, buf_to_snode_last_use, candidate_buffer_map
2024
+ )
2025
+ )
2026
+
2027
+ potential_peak, _post_alloc_update, _size_free_delta_update = (
2028
+ _calculate_potential_peak_memory_sink_waits(
2029
+ candidate,
2030
+ gns,
2031
+ group_head,
2032
+ group_peak_memory,
2033
+ candidate_delta_mem,
2034
+ candidate_allocfree,
2035
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
2036
+ _curr_memory,
2037
+ snodes_allocfree,
2038
+ )
2039
+ )
2040
+ if (
2041
+ potential_peak - peak_memory
2042
+ > peak_memory * config_comms.sink_iterative_peak_memory_budget
2043
+ ):
2044
+ info.limiting_factor = (
2045
+ f"peak memory new:{potential_peak} vs base:{peak_memory}"
2046
+ )
2047
+ break
2048
+
2049
+ info.moves += 1
2050
+ info.moves_info += f"+{candidate.get_name()}"
2051
+
2052
+ _head = _perform_double_linked_list_swap_sink_waits(
2053
+ candidate, group_head, group_tail, _prev, _next, _head
2054
+ )
2055
+
2056
+ comm_time, comp_time, overlap_info = _wait_exposed_communication_time(
2057
+ curr, _head, _prev, runtimes, node_output_sets, node_dep_sets
2058
+ )
2059
+ info.comm_time = comm_time
2060
+ info.comp_time = comp_time
2061
+ info.final_exposed = comm_time - comp_time
2062
+ info.overlap_info = overlap_info
2063
+
2064
+ _update_memory_tracking_after_swap_sink_waits(
2065
+ candidate,
2066
+ gns,
2067
+ candidate_delta_mem,
2068
+ candidate_allocfree,
2069
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
2070
+ _post_alloc_update,
2071
+ _size_free_delta_update,
2072
+ _curr_memory,
2073
+ snodes_allocfree,
2074
+ )
2075
+
2076
+ if debug_iterative_memory_recompute:
2077
+ from .comms_debug import _debug_iterative_memory_recompute
2078
+
2079
+ iterative_recompute_error = _debug_iterative_memory_recompute(
2080
+ candidate,
2081
+ gns,
2082
+ _group_names(gns),
2083
+ _group_nodes_from_linked_list(_head, None, _next),
2084
+ name_to_freeable_input_buf,
2085
+ graph_outputs,
2086
+ peak_memory,
2087
+ _curr_memory,
2088
+ snodes_allocfree,
2089
+ "sink_waits_iterative",
2090
+ group_n_to_bufs_after_swap_dealloc_instead_of_candidate,
2091
+ )
2092
+ if iterative_recompute_error:
2093
+ break
2094
+
2095
+ candidate = _next[group_tail]
2096
+ curr = _prev_curr
2097
+
2098
+ if not config_comms.reorder_sink_verbose_logging:
2099
+ new_snodes = _group_nodes_from_linked_list(_head, None, _next)
2100
+ return new_snodes, stats
2101
+
2102
+ new_snodes = _format_and_log_sink_waits_stats(
2103
+ stats,
2104
+ _head,
2105
+ _next,
2106
+ original_snodes_num,
2107
+ peak_memory,
2108
+ name_to_freeable_input_buf,
2109
+ graph_outputs,
2110
+ )
2111
+
2112
+ return new_snodes, stats
2113
+
2114
+
2115
+ def sink_waits_iterative(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
2116
+ """
2117
+ Similarly to reorder_communication_preserving_peak_memory this pass will try to iteratively
2118
+ push Wait nodes later, recomputing estimated peak memory before each swap,
2119
+ and preventing peak memory regressions.
2120
+
2121
+ Pass will be applied to every Wait node. If there are immediate dependencies with next node,
2122
+ pass will try to group them together and on the next step to swap the group with next candidate.
2123
+
2124
+ If _inductor.config_comms.sink_iterative_use_runtime_estimations is set True,
2125
+ pass will stop reordering of Wait once corresponding Collective is unexposed,
2126
+ based on runtime estimations.
2127
+
2128
+ inductor.config_comms.sink_iterative_peak_memory_budget allows to tune how much pass
2129
+ can regress initial peak memory.
2130
+ E.g.:
2131
+ sink_iterative_peak_memory_budget == 0.0 - No regression of initial peak memory is allowed
2132
+ sink_iterative_peak_memory_budget == 0.2 - Pass can improve comm-compute overlap, sacrificing
2133
+ 20% of initial peak memory value.
2134
+
2135
+ inductor.config_comms.sink_iterative_extra_comm_comp_overlap config allows to more aggressively
2136
+ sink waits, stopping only when overlap_compute >= (1 + extra_comm_comp_overlap) * comm_time
2137
+ """
2138
+ return _sink_waits_iterative_internal(snodes)[0]
2139
+
2140
+
2141
+ def estimate_op_runtime(snode: BaseSchedulerNode) -> float:
2142
+ """
2143
+ Returns estimated op runtime in milliseconds (ms)
2144
+ """
2145
+ if config.estimate_op_runtime == "default":
2146
+ runtime = snode.get_estimated_runtime()
2147
+ else:
2148
+ if not callable(config.estimate_op_runtime):
2149
+ raise AssertionError("expected config.estimate_op_runtime to be callable")
2150
+ runtime = config.estimate_op_runtime(snode)
2151
+ return runtime
2152
+
2153
+
2154
+ def node_summary(snode):
2155
+ snodes = snode.get_nodes()
2156
+ if len(snodes) == 1:
2157
+ detail = ""
2158
+ if isinstance(snode.node, (ir.ExternKernelOut, ir._CollectiveKernel)):
2159
+ outs_str = f"outs:{[o.get_name() for o in snode.get_outputs()]}"
2160
+ ins_str = f"ins:{[d.name for d in snode.unmet_dependencies]}"
2161
+ detail = f" {snode.get_name()} ({snode.node.python_kernel_name})\n {outs_str}({ins_str})"
2162
+ layouts = [child.node.get_output_spec() for child in snode.get_nodes()]
2163
+ out_tensor_info = ",".join(
2164
+ [
2165
+ f" (size={layout.size}, stride={layout.stride})"
2166
+ if isinstance(layout, ir.Layout)
2167
+ else ""
2168
+ for layout in layouts
2169
+ ]
2170
+ )
2171
+ try:
2172
+ node_name = snode.node.maybe_get_name()
2173
+ except AttributeError:
2174
+ # TODO: node_summary was written without FusedSchedulerNode in mind, generally needs to be hardened
2175
+ node_name = ""
2176
+ return f"{snode.node.__class__.__name__}{detail}{out_tensor_info} ({node_name} ({snode.get_estimated_runtime():.0f} ns)"
2177
+
2178
+ # Flatten the summaries for Fused/Foreach/Grouped nodes
2179
+ summaries = []
2180
+ for child_snode in snodes:
2181
+ summaries.append(node_summary(child_snode))
2182
+ return f"{snode.__class__.__name__}: {', '.join(summaries)}"
2183
+
2184
+
2185
+ def visualize_overlap(order):
2186
+ # TODO - this function probably doesn't do a very good job estimating the runtime because it doesn't carefully model
2187
+ # streams and overlap. For now its mostly useful as a debug visualization.
2188
+
2189
+ total_est_runtime: float = 0.0
2190
+ cur_comm_node = None
2191
+
2192
+ def step_log(step, msg):
2193
+ overlap_log.debug(f"{step:>6}: {msg}")
2194
+
2195
+ for step, snode in enumerate(order):
2196
+ if cur_comm_node is None:
2197
+ if contains_collective(snode):
2198
+ total_est_runtime += estimate_op_runtime(snode)
2199
+ cur_comm_node = snode.node
2200
+ elif is_wait(snode.node):
2201
+ # raise AssertionError(
2202
+ # "Wait is not expected when there is no collective running"
2203
+ # )
2204
+ pass
2205
+ else: # exposed compute op
2206
+ total_est_runtime += estimate_op_runtime(snode)
2207
+ step_log(step, f"{node_summary(snode)}")
2208
+ else: # cur_comm_node is not None
2209
+ if contains_collective(snode):
2210
+ total_est_runtime += estimate_op_runtime(snode)
2211
+ cur_comm_node = snode.node
2212
+ step_log(step, f"{node_summary(snode)}")
2213
+ elif is_wait(snode.node): # end of this comm op
2214
+ step_log(step, f"{node_summary(snode)}")
2215
+ cur_comm_node = None
2216
+ else: # overlapped compute op
2217
+ step_log(step, f"| {node_summary(snode)}")
2218
+ overlap_log.debug(f"Est. runtime (ms): {total_est_runtime / 1000 / 1000}")
2219
+
2220
+
2221
+ def simple_overlap(snodes: list[BaseSchedulerNode]) -> list[BaseSchedulerNode]:
2222
+ """Move collectives earlier and waits later via adjacent swaps.
2223
+ Each swap is safe: no collective reordering, no memory regression."""
2224
+ if len(snodes) < 2:
2225
+ return snodes
2226
+
2227
+ collectives = [s for s in snodes if contains_async_collective(s)]
2228
+ waits = [s for s in snodes if contains_wait(s)]
2229
+ if not collectives and not waits:
2230
+ return snodes
2231
+
2232
+ outputs_of: dict[BaseSchedulerNode, frozenset[str]] = {
2233
+ s: frozenset(o.get_name() for o in s.get_outputs()) for s in snodes
2234
+ }
2235
+ # Fake WeakDeps encode ordering-only constraints, such as collective order.
2236
+ deps_of: dict[BaseSchedulerNode, frozenset[str]] = {
2237
+ s: frozenset(d.name for d in s.unmet_dependencies) for s in snodes
2238
+ }
2239
+
2240
+ _prev, _next, _head = _initialize_double_linked_list(snodes)
2241
+ (
2242
+ peak_memory,
2243
+ _curr_memory,
2244
+ snodes_allocfree,
2245
+ _buf_last_use,
2246
+ _freeable,
2247
+ _cand_buf_map,
2248
+ ) = _initialize_memory_tracking(snodes)
2249
+
2250
+ n_moved_colls = 0
2251
+ n_moved_waits = 0
2252
+
2253
+ def peak_memory_safe_swap(
2254
+ candidate: BaseSchedulerNode,
2255
+ group_node: BaseSchedulerNode,
2256
+ *,
2257
+ sink_wait: bool,
2258
+ ) -> bool:
2259
+ nonlocal _head
2260
+
2261
+ group_nodes = [group_node]
2262
+ candidate_af = snodes_allocfree[candidate]
2263
+ candidate_delta = candidate_af.size_alloc - candidate_af.size_free
2264
+ size_free_cache: dict[BaseSchedulerNode, int] = {}
2265
+
2266
+ if sink_wait:
2267
+ changed_bufs = _find_buffers_with_changed_last_use_sink_waits(
2268
+ candidate, group_nodes, _buf_last_use, _cand_buf_map
2269
+ )
2270
+ potential_peak, post_alloc_cache, size_free_cache = (
2271
+ _calculate_potential_peak_memory_sink_waits(
2272
+ candidate,
2273
+ group_nodes,
2274
+ group_node,
2275
+ _curr_memory[group_node][0],
2276
+ candidate_delta,
2277
+ candidate_af,
2278
+ changed_bufs,
2279
+ _curr_memory,
2280
+ snodes_allocfree,
2281
+ )
2282
+ )
2283
+ else:
2284
+ changed_bufs = _find_buffers_with_changed_last_use(
2285
+ candidate, group_nodes, _buf_last_use, _cand_buf_map
2286
+ )
2287
+ potential_peak, post_alloc_cache = _calculate_potential_peak_memory_reorder(
2288
+ candidate,
2289
+ group_nodes,
2290
+ group_node,
2291
+ _curr_memory[group_node][0],
2292
+ candidate_delta,
2293
+ candidate_af,
2294
+ changed_bufs,
2295
+ _curr_memory,
2296
+ )
2297
+
2298
+ if potential_peak > peak_memory:
2299
+ return False
2300
+
2301
+ if sink_wait:
2302
+ _head = _perform_double_linked_list_swap_sink_waits(
2303
+ candidate, group_node, group_node, _prev, _next, _head
2304
+ )
2305
+ _update_memory_tracking_after_swap_sink_waits(
2306
+ candidate,
2307
+ group_nodes,
2308
+ candidate_delta,
2309
+ candidate_af,
2310
+ changed_bufs,
2311
+ post_alloc_cache,
2312
+ size_free_cache,
2313
+ _curr_memory,
2314
+ snodes_allocfree,
2315
+ )
2316
+ else:
2317
+ _head = _perform_double_linked_list_swap(
2318
+ candidate, group_node, group_node, _prev, _next, _head
2319
+ )
2320
+ _update_memory_tracking_after_swap_reorder(
2321
+ candidate,
2322
+ group_nodes,
2323
+ group_node,
2324
+ candidate_delta,
2325
+ candidate_af,
2326
+ changed_bufs,
2327
+ post_alloc_cache,
2328
+ _curr_memory,
2329
+ _buf_last_use,
2330
+ snodes_allocfree,
2331
+ )
2332
+
2333
+ return True
2334
+
2335
+ # Phase 1: move each collective earlier via adjacent swaps
2336
+ # Swap [pred, coll] -> [coll, pred]: pred is the "candidate" (moves later)
2337
+ for coll in collectives:
2338
+ coll_deps = deps_of[coll]
2339
+ moved = False
2340
+
2341
+ pred = _prev[coll]
2342
+ while pred is not None:
2343
+ if outputs_of[pred] & coll_deps:
2344
+ break
2345
+ if contains_async_collective(pred):
2346
+ break
2347
+ if not peak_memory_safe_swap(pred, coll, sink_wait=False):
2348
+ break
2349
+
2350
+ moved = True
2351
+ pred = _prev[coll]
2352
+
2353
+ if moved:
2354
+ n_moved_colls += 1
2355
+
2356
+ # Phase 2: move each wait later via adjacent swaps
2357
+ # Swap [wait, succ] -> [succ, wait]: succ is the "candidate" (moves earlier)
2358
+ for wait in reversed(waits):
2359
+ wait_outs = outputs_of[wait]
2360
+ moved = False
2361
+
2362
+ succ = _next[wait]
2363
+ while succ is not None:
2364
+ if deps_of[succ] & wait_outs:
2365
+ break
2366
+ if contains_wait(succ):
2367
+ break
2368
+ if not peak_memory_safe_swap(succ, wait, sink_wait=True):
2369
+ break
2370
+
2371
+ moved = True
2372
+ succ = _next[wait]
2373
+
2374
+ if moved:
2375
+ n_moved_waits += 1
2376
+
2377
+ if n_moved_colls or n_moved_waits:
2378
+ log.info(
2379
+ "simple_overlap: moved %d collectives, %d waits (peak %d MB)",
2380
+ n_moved_colls,
2381
+ n_moved_waits,
2382
+ peak_memory // (1024 * 1024),
2383
+ )
2384
+
2385
+ return _group_nodes_from_linked_list(_head, None, _next)
2386
+
2387
+
2388
+ def reorder_compute_and_comm_for_overlap(
2389
+ snodes: list[BaseSchedulerNode],
2390
+ ) -> list[BaseSchedulerNode]:
2391
+ order = snodes
2392
+ # pyrefly: ignore [bad-assignment]
2393
+ for p in config.reorder_for_compute_comm_overlap_passes:
2394
+ if isinstance(p, str) and p in globals():
2395
+ p = globals()[p] # it is a builtin pass
2396
+ if not callable(p):
2397
+ raise AssertionError(
2398
+ f"Invalid reorder_compute_and_comm_for_overlap pass: {p} is not callable"
2399
+ )
2400
+ order = p(order) # type: ignore[operator]
2401
+ # pyrefly: ignore [bad-return]
2402
+ return order
.venv/lib/python3.12/site-packages/torch/_inductor/comms_debug.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from torch._logging import trace_structured
6
+
7
+ from .memory import estimate_peak_memory_allocfree
8
+
9
+
10
+ if TYPE_CHECKING:
11
+ from torch.utils._ordered_set import OrderedSet
12
+
13
+ from .memory import FreeableInputBuffer, SNodeMemory
14
+ from .scheduler import BaseSchedulerNode, SchedulerBuffer
15
+
16
+
17
+ def _debug_iterative_memory_recompute(
18
+ candidate: BaseSchedulerNode,
19
+ gns: list[BaseSchedulerNode],
20
+ group_names: str,
21
+ snodes: list[BaseSchedulerNode],
22
+ name_to_freeable_input_buf: dict[str, FreeableInputBuffer],
23
+ graph_outputs: OrderedSet[str],
24
+ peak_memory: int,
25
+ iter_curr_memory: dict[BaseSchedulerNode, tuple[int, int]],
26
+ snodes_allocfree: dict[BaseSchedulerNode, SNodeMemory],
27
+ tlparse_name: str,
28
+ gn_to_bufs_last_use: dict[
29
+ BaseSchedulerNode, list[FreeableInputBuffer | SchedulerBuffer]
30
+ ],
31
+ ) -> bool:
32
+ iterative_recompute_error = False
33
+ candidate_allocfree = snodes_allocfree[candidate]
34
+ est_peak_memory, snodes_curr_memory, snodes_allocfree, _ = (
35
+ estimate_peak_memory_allocfree(
36
+ snodes, name_to_freeable_input_buf, graph_outputs
37
+ )
38
+ )
39
+ est_curr_memory = dict(zip(snodes, snodes_curr_memory))
40
+ iter_cm = iter_curr_memory[candidate]
41
+ new_cm = est_curr_memory[candidate]
42
+ log = ""
43
+ if est_peak_memory > peak_memory:
44
+ log = "ITERATIVE PEAK DOES NOT MATCH"
45
+ iterative_recompute_error = True
46
+ if iter_cm != new_cm:
47
+ log = "ITERATIVE CURR MEMORY CANDIDATE DOES NOT MATCH"
48
+ iterative_recompute_error = True
49
+ for gn in gns:
50
+ iter_gnm = iter_curr_memory[gn]
51
+ new_gnm = est_curr_memory[gn]
52
+ if iter_gnm != new_gnm:
53
+ log = f"ITERATIVE GN CURR MEMORY DOES NOT MATCH:{gn.get_name()}"
54
+ iterative_recompute_error = True
55
+ if iterative_recompute_error:
56
+ log += (
57
+ f"\nCANDIDATE:{candidate.get_name()}"
58
+ f"\nGROUP:{group_names}"
59
+ f"\nPEAK_MEMORY_BEFORE:{peak_memory}"
60
+ f"\nPEAK_MEMORY_AFTER_SWAP:{est_peak_memory}"
61
+ f"\nCANDIDATE:{candidate.debug_str()}"
62
+ f"\nCANDIDATE_ITER_CURR_MEMORY:{iter_cm}"
63
+ f"\nCANDIDATE_NEW__CURR_MEMORY:{new_cm}"
64
+ f"\nCANDIDATE_ITER_ALLOCFREE:{candidate_allocfree}"
65
+ f"\nCANDIDATE_NEW_ALLOCFREE:{snodes_allocfree[candidate]}"
66
+ )
67
+ peak_log = ""
68
+ for i, (pre, _post) in enumerate(snodes_curr_memory):
69
+ if est_peak_memory == pre:
70
+ n = snodes[i]
71
+ peak_log = (
72
+ f"\nNEW_PEAK:{est_peak_memory}(BASE:{peak_memory})"
73
+ f" @ SNODE[{i}/{len(snodes)}]:{n.get_name()} {n.debug_str()}"
74
+ )
75
+ break
76
+ group_log = ""
77
+ for i, gn in enumerate(gns):
78
+ iter_gnm = iter_curr_memory[gn]
79
+ new_gnm = est_curr_memory[gn]
80
+ group_log += (
81
+ f"\nGROUP_NODE[{i}]:{gn.debug_str()}"
82
+ f"\nGROUP_NODE[{i}] ITER_GNM[{gn.get_name()}]:{iter_gnm}"
83
+ f"\nGROUP_NODE[{i}] ESTM_GNM[{gn.get_name()}]:{new_gnm}"
84
+ f"\nGROUP_NODE[{i}] ITER_allocfree:{snodes_allocfree[gn]}"
85
+ f"\nGROUP_NODE[{i}] ESTM_allocfree:{snodes_allocfree[gn]}"
86
+ )
87
+ log += peak_log
88
+ log += group_log
89
+ log += f"\nGN_TO_BUFS_LAST_USE:{gn_to_bufs_last_use}"
90
+ log += "\n\n".join(
91
+ [
92
+ (
93
+ f"\nSNODE[{i}]\n{n.debug_str()}"
94
+ f"\nITER_cur_mem:{iter_curr_memory[n]}"
95
+ f"\nESTM_cur_mem:{est_curr_memory[n]}"
96
+ f"\nITER_allocfree:{snodes_allocfree[n]}"
97
+ f"\nESTM_allocfree:{snodes_allocfree[n]}"
98
+ )
99
+ for i, n in enumerate(snodes)
100
+ ]
101
+ )
102
+ tname = f"{tlparse_name}_ITERATIVE_RECOMPUTE_ERROR"
103
+ print(f"{tname}:\n{log}")
104
+ trace_structured(
105
+ "artifact",
106
+ metadata_fn=lambda: {
107
+ "name": tname,
108
+ "encoding": "string",
109
+ },
110
+ payload_fn=lambda: log,
111
+ )
112
+ return iterative_recompute_error
.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_async.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ from collections import deque
4
+ from dataclasses import dataclass
5
+ from typing import Any, TYPE_CHECKING
6
+ from typing_extensions import final, override
7
+
8
+ import torch._inductor.async_compile # noqa: F401 required to warm up AsyncCompile pools
9
+ from torch._inductor.output_code import (
10
+ CompiledFxGraph,
11
+ CompiledFxGraphConstants,
12
+ OutputCode,
13
+ )
14
+
15
+ from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile
16
+
17
+
18
+ # When async compile works with cache, remove the disabling below
19
+ BUG_CACHES_DONT_WORK_WITH_ASYNC = True
20
+
21
+
22
+ if TYPE_CHECKING:
23
+ from collections.abc import Callable, Sequence
24
+ from concurrent.futures import Future
25
+
26
+ from torch._inductor.utils import InputType
27
+ from torch.fx import GraphModule
28
+
29
+ from .compile_fx_ext import _OutOfProcessFxCompile, _WireProtocolPickledOutput
30
+
31
+
32
+ @dataclass
33
+ class _PostCompileData:
34
+ example_inputs: Sequence[InputType]
35
+ constants: CompiledFxGraphConstants
36
+ graph_kwargs: _CompileFxKwargs
37
+
38
+
39
+ @dataclass
40
+ class ProgressiveCompilationState:
41
+ progression_futures: deque[Future[_WireProtocolPickledOutput]]
42
+ callback: Callable[[_WireProtocolPickledOutput], OutputCode]
43
+ post_compile_data: _PostCompileData | None
44
+
45
+ def check_and_get_ready_stage(self) -> int:
46
+ """Check if any progression stage is ready and return its index, or -1 if none are ready."""
47
+ if not self.progression_futures:
48
+ return -1
49
+
50
+ stage_index = -1
51
+ if self.post_compile_data:
52
+ for i, future in enumerate(self.progression_futures):
53
+ if future.done():
54
+ stage_index = i
55
+
56
+ return stage_index
57
+
58
+ def switch_to_progression_stage(self, stage_index: int) -> tuple[OutputCode, bool]:
59
+ """
60
+ Switch to the specified progression stage and return the optimized output code.
61
+ Returns a tuple of (optimized_output_code, should_clear_compilation_state).
62
+ """
63
+ future = self.progression_futures[stage_index]
64
+ if future is None:
65
+ raise AssertionError("expected future to be not None")
66
+ optimized_output_code = self.callback(future.result())
67
+
68
+ if pcd := self.post_compile_data:
69
+ optimized_output_code.post_compile(
70
+ pcd.example_inputs, pcd.constants, pcd.graph_kwargs
71
+ )
72
+
73
+ # Clear earlier progression futures to free memory
74
+ for _ in range(stage_index + 1):
75
+ self.progression_futures.popleft()
76
+
77
+ # Return whether all compilation state should be cleared
78
+ should_clear_state = not self.progression_futures
79
+ return optimized_output_code, should_clear_state
80
+
81
+
82
+ # _AsyncOutputCode handles the actual management of waiting for an
83
+ # out-of-process compile to finish and then switching over to it.
84
+ @final
85
+ class _AsyncOutputCode(OutputCode):
86
+ _eager_fn: Callable[..., Any] | None
87
+ _output_code: OutputCode | None
88
+ _future: Future[_WireProtocolPickledOutput] | None
89
+ _callback: Callable[[_WireProtocolPickledOutput], OutputCode]
90
+ _post_compile_data: _PostCompileData | None = None
91
+ _boxed_call: bool # Copied from the forward/output_code
92
+
93
+ def __init__(
94
+ self,
95
+ # eager_fn is run until the future is finished.
96
+ eager_fn: Callable[..., Any],
97
+ # this responds with the result of the out-of-process compile when it's
98
+ # ready.
99
+ future: Future[_WireProtocolPickledOutput],
100
+ # this callback gets called to turn the _WireProtocolPickledOutput into an OutputCode
101
+ callback: Callable[[_WireProtocolPickledOutput], OutputCode],
102
+ ) -> None:
103
+ self._eager_fn = eager_fn
104
+ self._boxed_call = getattr(eager_fn, "_boxed_call", False)
105
+ self._output_code = None
106
+
107
+ self._future = future
108
+ self._callback = callback
109
+
110
+ @override
111
+ def __call__(self, *args: Any) -> Any:
112
+ if self._future is not None and self._future.done():
113
+ args = self._switch_to_compiled_fn(args)
114
+
115
+ if eager_fn := self._eager_fn:
116
+ _AsyncFxCompile._stat_eager_runs += 1
117
+ return eager_fn(*args)
118
+
119
+ else:
120
+ _AsyncFxCompile._stat_compiled_runs += 1
121
+ if self._output_code is None:
122
+ raise AssertionError("expected self._output_code to be not None")
123
+ return self._output_code.__call__(*args)
124
+
125
+ # Takes and returns the args (converted to the "right" boxed mode)
126
+ def _switch_to_compiled_fn(self, args: tuple[Any, ...]) -> tuple[Any, ...]:
127
+ if self._future is None:
128
+ raise AssertionError("expected self._future to be not None")
129
+
130
+ # TODO: If the future ended in an exception do we want to continue
131
+ # running eager or hit the exception now?
132
+ f, self._future = self._future, None
133
+ output_code = self._callback(f.result())
134
+
135
+ if pcd := self._post_compile_data:
136
+ self._post_compile_data = None
137
+
138
+ output_code.post_compile(
139
+ pcd.example_inputs, pcd.constants, pcd.graph_kwargs
140
+ )
141
+
142
+ self._output_code = output_code
143
+ self._eager_fn = None
144
+ boxed_call = getattr(output_code, "_boxed_call", False)
145
+
146
+ if self._boxed_call != boxed_call:
147
+ if self._boxed_call:
148
+ # Was boxed, now unboxed
149
+ args = args[0] if len(args) > 0 else ()
150
+ else:
151
+ # Was unboxed, now boxed
152
+ args = (args,)
153
+
154
+ self._boxed_call = boxed_call
155
+ return args
156
+
157
+ @override
158
+ def post_compile(
159
+ self,
160
+ example_inputs: Sequence[InputType],
161
+ constants: CompiledFxGraphConstants,
162
+ graph_kwargs: _CompileFxKwargs,
163
+ ) -> None:
164
+ if self._eager_fn is not None:
165
+ self._post_compile_data = _PostCompileData(
166
+ example_inputs, constants, graph_kwargs
167
+ )
168
+ else:
169
+ if self._output_code is None:
170
+ raise AssertionError("expected self._output_code to be not None")
171
+ self._output_code.post_compile(example_inputs, constants, graph_kwargs)
172
+
173
+
174
+ # Given an FxCompile for an out-of-process compile _AsyncFxCompile will run
175
+ # eager until the compiled artifact is ready then it will automatically switch
176
+ # over to using the compiled version.
177
+ @final
178
+ class _AsyncFxCompile(FxCompile):
179
+ _compile: _OutOfProcessFxCompile
180
+
181
+ # Some debugging stats:
182
+ # Number of times we started a background compile.
183
+ _stat_bg_started: int = 0
184
+ # Number of times we finished a background compile.
185
+ _stat_bg_finished: int = 0
186
+ # Number of times we ran "eager"
187
+ _stat_eager_runs: int = 0
188
+ # Number of times we ran our compiled (out-of-process) artifact
189
+ _stat_compiled_runs: int = 0
190
+
191
+ def __init__(self, compile: _OutOfProcessFxCompile) -> None:
192
+ self._compile = compile
193
+
194
+ @classmethod
195
+ def _reset_stats(cls) -> None:
196
+ cls._stat_bg_started = 0
197
+ cls._stat_bg_finished = 0
198
+ cls._stat_eager_runs = 0
199
+ cls._stat_compiled_runs = 0
200
+
201
+ @override
202
+ def codegen_and_compile(
203
+ self,
204
+ gm: GraphModule,
205
+ example_inputs: Sequence[InputType],
206
+ inputs_to_check: Sequence[int],
207
+ graph_kwargs: _CompileFxKwargs,
208
+ ) -> OutputCode:
209
+ eager_compile = _InProcessFxCompile()
210
+ eager_compile.compile_region_name = self.compile_region_name
211
+ eager_output_code = eager_compile.codegen_and_compile(
212
+ gm, example_inputs, inputs_to_check, graph_kwargs
213
+ )
214
+
215
+ # This is similar to _SerializedFxCompile.codegen_and_compile() but
216
+ # handles the async routing.
217
+
218
+ serialized = self._compile.serialize_compile(
219
+ gm, example_inputs, inputs_to_check, graph_kwargs
220
+ )
221
+ if not serialized:
222
+ # We can't serialize - just return the eager OutputCode
223
+ return eager_output_code
224
+
225
+ inputs, constants = serialized
226
+
227
+ _AsyncFxCompile._stat_bg_started += 1
228
+ f = self._compile._send_to_child_async(inputs)
229
+
230
+ # This is called by _switch_to_compiled_fn() when f has a result...
231
+ def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode:
232
+ _AsyncFxCompile._stat_bg_finished += 1
233
+ output = pickled_output.deserialize(constants)
234
+ if isinstance(output.graph, CompiledFxGraph):
235
+ output.graph.compile_region_name = self.compile_region_name
236
+ self._compile._postprocess(output)
237
+ return output.graph
238
+
239
+ return _AsyncOutputCode(eager_output_code, f, callback)
240
+
241
+
242
+ # _ProgressiveOutputCode handles running a fast compile first, then hot-swapping
243
+ # to a more optimized version when the expensive compile finishes.
244
+ @final
245
+ class _ProgressiveOutputCode(OutputCode):
246
+ _fast_output_code: OutputCode | None
247
+ _optimized_output_code: OutputCode | None
248
+ _compilation_state: ProgressiveCompilationState | None
249
+ # _boxed_call state is effectively cached (we sometimes wrap unboxed w/
250
+ # lambdas to box them) so we can't change it mid-way. Since _boxed_call=True
251
+ # is more common let's default to that and we'll convert if necessary.
252
+ _boxed_call: bool = True
253
+
254
+ def __init__(
255
+ self,
256
+ # Fast compile that runs faster than the progressive compiles
257
+ fast_output_code: OutputCode,
258
+ # Futures for the progressive optimized compiles
259
+ progression_futures: Sequence[Future[_WireProtocolPickledOutput]],
260
+ # Callback to convert the optimized result to OutputCode
261
+ callback: Callable[[_WireProtocolPickledOutput], OutputCode],
262
+ ) -> None:
263
+ self._fast_output_code = fast_output_code
264
+ self._optimized_output_code = None
265
+ self._compilation_state = ProgressiveCompilationState(
266
+ progression_futures=deque(progression_futures),
267
+ callback=callback,
268
+ post_compile_data=None,
269
+ )
270
+
271
+ @override
272
+ def __call__(self, args: Sequence[Any]) -> Any:
273
+ # Check if any newer progression stage is ready and switch to it
274
+ self._check_and_switch_progression()
275
+
276
+ if self._optimized_output_code is not None:
277
+ _ProgressiveFxCompile._stat_optimized_runs += 1
278
+ output_code = self._optimized_output_code
279
+ else:
280
+ _ProgressiveFxCompile._stat_fast_runs += 1
281
+ if self._fast_output_code is None:
282
+ raise AssertionError("expected self._fast_output_code to be not None")
283
+ output_code = self._fast_output_code
284
+
285
+ boxed_call = getattr(output_code, "_boxed_call", False)
286
+ if boxed_call:
287
+ res = output_code.__call__(args)
288
+ else:
289
+ res = output_code.__call__(*args)
290
+ return res
291
+
292
+ def _check_and_switch_progression(self) -> None:
293
+ if not self._compilation_state:
294
+ return
295
+
296
+ stage_index = self._compilation_state.check_and_get_ready_stage()
297
+ if stage_index == -1:
298
+ # no futures are ready
299
+ return
300
+
301
+ self._switch_to_progression_stage(stage_index)
302
+
303
+ def _switch_to_progression_stage(self, stage_index: int) -> None:
304
+ if self._compilation_state is None:
305
+ raise AssertionError("expected self._compilation_state to be not None")
306
+ optimized_output_code, should_clear_state = (
307
+ self._compilation_state.switch_to_progression_stage(stage_index)
308
+ )
309
+
310
+ self._optimized_output_code = optimized_output_code
311
+ self._fast_output_code = None
312
+
313
+ # Clear all compilation state if no more progression futures are left
314
+ if should_clear_state:
315
+ self._compilation_state = None
316
+
317
+ @override
318
+ def post_compile(
319
+ self,
320
+ example_inputs: Sequence[InputType],
321
+ constants: CompiledFxGraphConstants,
322
+ graph_kwargs: _CompileFxKwargs,
323
+ ) -> None:
324
+ if self._fast_output_code is None:
325
+ raise AssertionError("expected self._fast_output_code to be not None")
326
+ self._fast_output_code.post_compile(example_inputs, constants, graph_kwargs)
327
+
328
+ if self._compilation_state is None:
329
+ raise AssertionError("expected self._compilation_state to be not None")
330
+ # Store for later when optimized version is ready
331
+ self._compilation_state.post_compile_data = _PostCompileData(
332
+ example_inputs, constants, graph_kwargs
333
+ )
334
+
335
+
336
+ # _ProgressiveFxCompile runs a fast compile immediately, then kicks off
337
+ # progressive compiles in the background and hot-swaps when they're ready.
338
+ @final
339
+ class _ProgressiveFxCompile(FxCompile):
340
+ _fast_compile: FxCompile
341
+ _optimized_compile: _OutOfProcessFxCompile
342
+ _progression_configs: list[dict[str, Any]]
343
+
344
+ # Debugging stats
345
+ _stat_bg_started: int = 0
346
+ _stat_bg_finished: int = 0
347
+ _stat_fast_runs: int = 0
348
+ _stat_optimized_runs: int = 0
349
+
350
+ def __init__(
351
+ self,
352
+ fast_compile: FxCompile,
353
+ optimized_compile: _OutOfProcessFxCompile,
354
+ progression_configs: list[dict[str, Any]],
355
+ ) -> None:
356
+ self._fast_compile = fast_compile
357
+ self._optimized_compile = optimized_compile
358
+ self._progression_configs = progression_configs
359
+
360
+ @classmethod
361
+ def _reset_stats(cls) -> None:
362
+ cls._stat_bg_started = 0
363
+ cls._stat_bg_finished = 0
364
+ cls._stat_fast_runs = 0
365
+ cls._stat_optimized_runs = 0
366
+
367
+ @override
368
+ def codegen_and_compile(
369
+ self,
370
+ gm: GraphModule,
371
+ example_inputs: Sequence[InputType],
372
+ inputs_to_check: Sequence[int],
373
+ graph_kwargs: _CompileFxKwargs,
374
+ ) -> OutputCode:
375
+ import torch._inductor.config as inductor_config
376
+
377
+ progression_futures: list[Future[_WireProtocolPickledOutput]] = []
378
+
379
+ for config in self._progression_configs:
380
+ with inductor_config.patch(config):
381
+ _ProgressiveFxCompile._stat_bg_started += 1
382
+
383
+ # Start the progressive compiles in the background
384
+ serialized = self._optimized_compile.serialize_compile(
385
+ gm, example_inputs, inputs_to_check, graph_kwargs
386
+ )
387
+
388
+ if not serialized:
389
+ continue
390
+
391
+ inputs, constants = serialized
392
+ future = self._optimized_compile._send_to_child_async(inputs)
393
+ progression_futures.append(future)
394
+
395
+ fast_output_code = self._fast_compile.codegen_and_compile(
396
+ gm, example_inputs, inputs_to_check, graph_kwargs
397
+ )
398
+
399
+ if not progression_futures:
400
+ # All async compile attempts failed - just return the fast version
401
+ return fast_output_code
402
+
403
+ # Callback to handle the optimized result.
404
+ # This callback may be called multiple times, once for each progressive level completed,
405
+ # but may be skipped if a level either never completes or if a more optimal level
406
+ # completes before a less optimal one is switched to.
407
+ def callback(pickled_output: _WireProtocolPickledOutput) -> OutputCode:
408
+ _ProgressiveFxCompile._stat_bg_finished += 1
409
+ output = pickled_output.deserialize(constants)
410
+ if isinstance(output.graph, CompiledFxGraph):
411
+ output.graph.compile_region_name = self.compile_region_name
412
+ self._optimized_compile._postprocess(output)
413
+ return output.graph
414
+
415
+ return _ProgressiveOutputCode(fast_output_code, progression_futures, callback)
.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_ext.py ADDED
@@ -0,0 +1,729 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import dataclasses
5
+ import functools
6
+ import logging
7
+ import os
8
+ import queue
9
+ import sys
10
+ import tempfile
11
+ import warnings
12
+ from abc import abstractmethod
13
+ from dataclasses import dataclass
14
+ from typing import Any, TYPE_CHECKING, TypeGuard
15
+ from typing_extensions import final, override, Self
16
+
17
+ import torch._inductor.async_compile
18
+ import torch.fx
19
+ from torch._inductor.codecache import BypassFxGraphCache, FxGraphCache
20
+ from torch._inductor.metrics import CachedMetricsDeltas, CachedMetricsHelper
21
+ from torch._inductor.output_code import (
22
+ CompiledFxGraph,
23
+ CompiledFxGraphConstants,
24
+ CompiledFxGraphConstantsWithGm,
25
+ OutputCode,
26
+ )
27
+ from torch._inductor.utils import patch_subprocess_env
28
+ from torch._subclasses import FakeTensorMode
29
+ from torch.utils._ordered_set import OrderedSet
30
+
31
+ from . import config
32
+ from .compile_fx import _CompileFxKwargs, _InProcessFxCompile, FxCompile, log
33
+ from .debug import DebugContext
34
+ from .graph import GraphLowering
35
+ from .virtualized import V
36
+
37
+
38
+ if TYPE_CHECKING:
39
+ import types
40
+ from collections.abc import Generator, Mapping, Sequence
41
+ from concurrent.futures import Future
42
+
43
+ from torch._inductor.utils import InputType
44
+ from torch.fx import GraphModule
45
+
46
+
47
+ def _graph_contains_triton_kernel_wrappers(gm: GraphModule) -> bool:
48
+ """
49
+ Check if the graph contains triton kernel wrapper nodes. These nodes contain
50
+ references to the kernel_side_table which is process-local and can't be
51
+ serialized across processes.
52
+ """
53
+ from torch._higher_order_ops.triton_kernel_wrap import (
54
+ triton_kernel_wrapper_functional,
55
+ triton_kernel_wrapper_mutation,
56
+ )
57
+
58
+ for module in gm.modules():
59
+ if not isinstance(module, torch.fx.GraphModule):
60
+ continue
61
+ for node in module.graph.nodes:
62
+ if node.target in (
63
+ triton_kernel_wrapper_functional,
64
+ triton_kernel_wrapper_mutation,
65
+ ):
66
+ return True
67
+ return False
68
+
69
+
70
+ @dataclass
71
+ class _VirtualizedSerializer:
72
+ """
73
+ This handles the data for serializing Virtualized.
74
+ """
75
+
76
+ # The values here get serialized. We don't grab everything because some of
77
+ # the fields can't be serialized.
78
+ aot_compilation: Any = None
79
+ choices: Any = None
80
+ local_buffer_context: Any = None
81
+ ops: Any = None
82
+ kernel: Any = None
83
+ current_node: Any = None
84
+
85
+ @classmethod
86
+ def serialize(cls) -> _VirtualizedSerializer:
87
+ """
88
+ Turn the current state of torch._inductor.virtualized.V into a
89
+ serializable structure.
90
+ """
91
+ kwargs = {}
92
+ for f in dataclasses.fields(cls):
93
+ kwargs[f.name] = getattr(V, f.name)
94
+ return _VirtualizedSerializer(**kwargs)
95
+
96
+ def patch(self) -> _VirtualizedSerializerContextManager:
97
+ """
98
+ Returns a context manager which patches the saved values into the
99
+ current environment. While patched, any value not listed above will be
100
+ poisoned so that reads will raise an error.
101
+ """
102
+ return _VirtualizedSerializerContextManager(self)
103
+
104
+
105
+ class _VirtualizedSerializerContextManager(contextlib.ExitStack):
106
+ """
107
+ Helper for _VirtualizedSerializer.patch()
108
+ """
109
+
110
+ def __init__(self, virtualized: _VirtualizedSerializer) -> None:
111
+ super().__init__()
112
+ self.virtualized = virtualized
113
+
114
+ @override
115
+ def __enter__(self) -> Self:
116
+ super().__enter__()
117
+
118
+ for set_name in dir(V):
119
+ if not set_name.startswith("set_"):
120
+ continue
121
+ name = set_name[4:]
122
+ name = name.removesuffix("_handler")
123
+ set_handler = getattr(V, set_name)
124
+ if hasattr(self.virtualized, name):
125
+ value = getattr(self.virtualized, name)
126
+ else:
127
+ # poison any values that we don't serialize so that any
128
+ # unset accesses are caught.
129
+ value = torch._inductor.virtualized._PoisonedVirtual
130
+ self.enter_context(set_handler(value))
131
+
132
+ return self
133
+
134
+
135
+ def _is_fallback_handler(op: object) -> bool:
136
+ try:
137
+ return op._is_fallback_handler # type: ignore[attr-defined]
138
+ except AttributeError:
139
+ return False
140
+
141
+
142
+ class _LoweringSerializer:
143
+ """
144
+ This handles the data for serializing lowering.lowering
145
+ """
146
+
147
+ # A full implementation would make sure that all lowerings are copied over
148
+ # (or at least detected and raise a bypass when a non-standard lowering is
149
+ # used). For now we just handle tests by looking for lowerings that were
150
+ # overridden with a forced fallback.
151
+ fallbacks: OrderedSet[str]
152
+
153
+ def __init__(self) -> None:
154
+ from . import lowering
155
+
156
+ self.fallbacks = OrderedSet(
157
+ str(k) for k, v in lowering.lowerings.items() if _is_fallback_handler(v)
158
+ )
159
+
160
+ def patch(self) -> _LoweringSerializerContextManager:
161
+ return _LoweringSerializerContextManager(self)
162
+
163
+
164
+ class _LoweringSerializerContextManager(contextlib.ExitStack):
165
+ """
166
+ Helper for _LoweringSerializer.patch()
167
+ """
168
+
169
+ def __init__(self, lowering: _LoweringSerializer) -> None:
170
+ super().__init__()
171
+ self.lowering = lowering
172
+
173
+ @override
174
+ def __enter__(self) -> Self:
175
+ super().__enter__()
176
+
177
+ from . import lowering
178
+
179
+ for k, v in lowering.lowerings.items():
180
+ name = str(k)
181
+ if name in self.lowering.fallbacks:
182
+ if not _is_fallback_handler(v):
183
+ self.enter_context(lowering.force_fallback(k)) # type: ignore[arg-type]
184
+
185
+ return self
186
+
187
+
188
+ @dataclass
189
+ class _FakeTensorModeSerializer:
190
+ allow_non_fake_inputs: bool
191
+
192
+ def __init__(self, fake_mode: FakeTensorMode) -> None:
193
+ self.allow_non_fake_inputs = fake_mode.allow_non_fake_inputs
194
+ self.shape_env = fake_mode.shape_env
195
+
196
+ @contextlib.contextmanager
197
+ def patch(self, fake_mode: FakeTensorMode) -> Generator[None, None, None]:
198
+ saved_allow_non_fake_inputs = fake_mode.allow_non_fake_inputs
199
+ fake_mode.allow_non_fake_inputs = self.allow_non_fake_inputs
200
+
201
+ yield
202
+
203
+ fake_mode.allow_non_fake_inputs = saved_allow_non_fake_inputs
204
+
205
+
206
+ @dataclass
207
+ class _WireProtocolInput:
208
+ """
209
+ For _SerializedFxCompile - encapsulates all the data being transferred
210
+ (sent) from the parent to the child.
211
+ """
212
+
213
+ gm: torch.fx.GraphModule
214
+ example_inputs: Sequence[InputType]
215
+ inputs_to_check: Sequence[int]
216
+ graph_kwargs: _CompileFxKwargs
217
+ tracing_context: torch._guards.TracingContext | None
218
+ config: dict[str, object]
219
+ virtualized: _VirtualizedSerializer
220
+ deterministic_guard_for_testing: ( # type: ignore[name-defined] # mypy bug
221
+ torch.testing._internal.common_utils.DeterministicGuard | None
222
+ )
223
+ logger_state: _LoggerState
224
+ lowering: _LoweringSerializer
225
+ fake_tensor_mode: _FakeTensorModeSerializer
226
+
227
+ def serialize(self) -> _WireProtocolPickledInput:
228
+ """
229
+ Turns this object into a _WireProtocolPickledInput which can be
230
+ directly transferred across a stream.
231
+ """
232
+ from torch.fx._graph_pickler import GraphPickler
233
+
234
+ return _WireProtocolPickledInput(GraphPickler.dumps(self))
235
+
236
+
237
+ def _current_fake_mode() -> FakeTensorMode:
238
+ fake_mode = None
239
+ if context := torch._guards.TracingContext.try_get():
240
+ fake_mode = context.fake_mode
241
+ if fake_mode is not None:
242
+ return fake_mode
243
+
244
+ shape_env = torch.fx.experimental.symbolic_shapes.ShapeEnv()
245
+ return FakeTensorMode(shape_env=shape_env)
246
+
247
+
248
+ @dataclass
249
+ class _WireProtocolPickledInput:
250
+ value: bytes
251
+
252
+ def deserialize(self) -> _WireProtocolInput:
253
+ """
254
+ Turn this streamable object back into a _WireProtocolInput.
255
+ """
256
+ from torch.fx._graph_pickler import GraphPickler
257
+
258
+ fake_mode = _current_fake_mode()
259
+ result = GraphPickler.loads(self.value, fake_mode)
260
+ if not isinstance(result, _WireProtocolInput):
261
+ raise AssertionError(f"expected _WireProtocolInput, got {type(result)}")
262
+ return result
263
+
264
+
265
+ @dataclass
266
+ class _WireProtocolOutput:
267
+ """
268
+ For _SerializedFxCompile - encapsulates all the data being transferred
269
+ (returned) back from the child to the parent.
270
+ """
271
+
272
+ graph: OutputCode
273
+ metrics: CachedMetricsDeltas
274
+ logs: list[logging.LogRecord]
275
+ warning_replay: list[warnings.WarningMessage] | None
276
+ shape_env: torch.fx.experimental.symbolic_shapes.ShapeEnv | None
277
+
278
+ def serialize(self) -> _WireProtocolPickledOutput:
279
+ """
280
+ Turns this object into a _WireProtocolPickledOutput which can be
281
+ directly transferred across a stream.
282
+ """
283
+ from torch.fx._graph_pickler import GraphPickler
284
+
285
+ if isinstance(self.graph, CompiledFxGraph):
286
+ self.graph.prepare_for_serialization()
287
+ return _WireProtocolPickledOutput(GraphPickler.dumps(self))
288
+
289
+
290
+ @dataclass
291
+ class _WireProtocolPickledOutput:
292
+ value: bytes
293
+
294
+ def deserialize(self, constants: CompiledFxGraphConstants) -> _WireProtocolOutput:
295
+ """
296
+ Turn this streamable object back into a _WireProtocolOutput.
297
+ """
298
+ from torch.fx._graph_pickler import GraphPickler
299
+
300
+ fake_mode = _current_fake_mode()
301
+ result = GraphPickler.loads(self.value, fake_mode)
302
+ if not isinstance(result, _WireProtocolOutput):
303
+ raise AssertionError(f"expected _WireProtocolOutput, got {type(result)}")
304
+ if isinstance(result.graph, CompiledFxGraph):
305
+ result.graph.after_deserialization(constants)
306
+ return result
307
+
308
+
309
+ class _LoggerState:
310
+ """
311
+ This class is for tracking logging that happens during an out-of-process
312
+ compile so we can "replay" those messages when the compile is done. Used as
313
+ a context manager which returns the captured logs (object).
314
+ """
315
+
316
+ loggers: dict[str, int]
317
+ # The actual log capturing mechanism - this should be None when we're not
318
+ # actively capturing logs.
319
+ captured_logs: _CapturedLogs | None = None
320
+
321
+ def __init__(self) -> None:
322
+ # Mapping from logger name to level.
323
+ self.loggers = {}
324
+
325
+ def filter(
326
+ logger: logging.Logger | logging.PlaceHolder,
327
+ ) -> TypeGuard[logging.Logger]:
328
+ if not isinstance(logger, logging.Logger):
329
+ # Assume that Placeholders propagate
330
+ return False
331
+ # We only want to track torch._inductor logging
332
+ if not logger.name.startswith("torch._inductor"):
333
+ return False
334
+ # If this logger propagates then assume we'll track its parent
335
+ if logger.propagate:
336
+ return False
337
+ return True
338
+
339
+ root = logging.getLogger("torch._inductor")
340
+ if sys.version_info < (3, 12):
341
+ # logging.getChildren() doesn't exist until 3.12
342
+ logging._acquireLock() # type: ignore[attr-defined]
343
+ try:
344
+ for logger in root.manager.loggerDict.values():
345
+ if filter(logger):
346
+ self.loggers[logger.name] = logger.level
347
+ finally:
348
+ logging._releaseLock() # type: ignore[attr-defined]
349
+ else:
350
+ q = [root]
351
+ while q:
352
+ logger = q.pop()
353
+ if filter(logger):
354
+ self.loggers[logger.name] = logger.level
355
+ q.extend(logger.getChildren())
356
+
357
+ def __enter__(self) -> _CapturedLogs:
358
+ if self.captured_logs is not None:
359
+ raise AssertionError("captured_logs already set on __enter__")
360
+ self.captured_logs = _CapturedLogs(self)
361
+ self.captured_logs.apply()
362
+ return self.captured_logs
363
+
364
+ def __exit__(
365
+ self,
366
+ exc_type: type[BaseException] | None,
367
+ exc_value: BaseException | None,
368
+ traceback: types.TracebackType | None,
369
+ ) -> None:
370
+ if self.captured_logs is None:
371
+ raise AssertionError("captured_logs not set on __exit__")
372
+ self.captured_logs.remove()
373
+
374
+
375
+ class _CapturedLogs:
376
+ """
377
+ Helper for _LoggerState - this class actually attaches to the logger in
378
+ the child process and grabs the log messages themselves.
379
+ """
380
+
381
+ state: _LoggerState
382
+ queue: queue.Queue[logging.LogRecord]
383
+ handlers: dict[str, logging.Handler] | None
384
+
385
+ def __init__(self, state: _LoggerState) -> None:
386
+ self.state = state
387
+ # A queue of the log entries
388
+ # TODO: For memory purposes should we log to a file and then respond with that?
389
+ self.queue = queue.Queue(-1)
390
+ # Mapping from name to handler (only valid when applied)
391
+ self.handlers = None
392
+
393
+ def finish(self) -> list[logging.LogRecord]:
394
+ if self.handlers is not None:
395
+ raise AssertionError("expected handlers to be None in finish")
396
+ logs = []
397
+ try:
398
+ while True:
399
+ logs.append(self.queue.get_nowait())
400
+ except queue.Empty:
401
+ pass
402
+ return logs
403
+
404
+ def remove(self) -> None:
405
+ if self.handlers is None:
406
+ raise AssertionError("expected handlers to be set in remove")
407
+ handlers, self.handlers = self.handlers, None
408
+ for name, handler in handlers.items():
409
+ logger = logging.getLogger(name)
410
+ logger.removeHandler(handler)
411
+
412
+ def apply(self) -> None:
413
+ from logging.handlers import QueueHandler
414
+
415
+ if self.handlers is not None:
416
+ raise AssertionError("expected handlers to be None in apply")
417
+ self.handlers = {}
418
+ for name, level in self.state.loggers.items():
419
+ logger = logging.getLogger(name)
420
+ handler = QueueHandler(self.queue)
421
+ self.handlers[name] = handler
422
+ logger.addHandler(handler)
423
+ if level != logging.NOTSET:
424
+ logger.setLevel(level)
425
+
426
+
427
+ class _SerializedFxCompile(FxCompile):
428
+ """
429
+ This is used to represent an FxCompile which occurs across a serialized
430
+ boundary.
431
+ """
432
+
433
+ @override
434
+ def codegen_and_compile(
435
+ self,
436
+ gm: GraphModule,
437
+ example_inputs: Sequence[InputType],
438
+ inputs_to_check: Sequence[int],
439
+ graph_kwargs: _CompileFxKwargs,
440
+ ) -> OutputCode:
441
+ # If this code changes it's likely _AsyncFxCompile.codegen_and_compile()
442
+ # will also need to match.
443
+
444
+ serialized = self.serialize_compile(
445
+ gm, example_inputs, inputs_to_check, graph_kwargs
446
+ )
447
+ if not serialized:
448
+ eager_compile = _InProcessFxCompile()
449
+ eager_compile.compile_region_name = self.compile_region_name
450
+ return eager_compile.codegen_and_compile(
451
+ gm, example_inputs, inputs_to_check, graph_kwargs
452
+ )
453
+
454
+ inputs, constants = serialized
455
+ output = self._send_to_child(inputs).deserialize(constants)
456
+ if isinstance(output.graph, CompiledFxGraph):
457
+ output.graph.compile_region_name = self.compile_region_name
458
+
459
+ self._postprocess(output)
460
+ self._compile_stats[type(self)].codegen_and_compile += 1
461
+
462
+ # TODO: Do we need to figure out what changed in TracingContext in the
463
+ # child and plumb that back up to the parent?
464
+
465
+ return output.graph
466
+
467
+ def serialize_compile(
468
+ self,
469
+ gm: GraphModule,
470
+ example_inputs: Sequence[InputType],
471
+ inputs_to_check: Sequence[int],
472
+ graph_kwargs: _CompileFxKwargs,
473
+ ) -> tuple[_WireProtocolPickledInput, CompiledFxGraphConstantsWithGm] | None:
474
+ """
475
+ Prepare a _WireProtocolInput to compile. If None is returned then it
476
+ wasn't possible to serialize and we should fallback to in-process.
477
+ """
478
+ try:
479
+ # _check_for_hop raises BypassFxGraphCache when it detects something
480
+ # we can't cache (or serialize)
481
+ FxGraphCache._check_for_hop(gm)
482
+ except BypassFxGraphCache as e:
483
+ log.debug("Skipping %s compile: %s", type(self), e)
484
+ return None
485
+
486
+ # Triton kernel wrapper nodes contain references to the kernel_side_table
487
+ # which is process-local and can't be serialized across processes.
488
+ if _graph_contains_triton_kernel_wrappers(gm):
489
+ log.debug(
490
+ "Skipping %s compile: graph contains triton kernel wrappers", type(self)
491
+ )
492
+ return None
493
+
494
+ context = torch._guards.TracingContext.try_get()
495
+ constants = CompiledFxGraphConstantsWithGm(gm)
496
+ logger_state = _LoggerState()
497
+ lowering = _LoweringSerializer()
498
+
499
+ # If we're running tests then grab the DeterministicGuard (don't want to
500
+ # import this if it isn't already imported because it has side-effects)
501
+ deterministic_guard_for_testing: ( # type: ignore[name-defined] # mypy bug
502
+ torch.testing._internal.common_utils.DeterministicGuard | None
503
+ ) = None
504
+ try:
505
+ deterministic_guard_for_testing = (
506
+ torch.testing._internal.common_utils.DeterministicGuard._current_state() # type: ignore[attr-defined] # mypy bug
507
+ )
508
+ except AttributeError:
509
+ pass
510
+
511
+ fake_mode = _current_fake_mode()
512
+ fake_tensor_mode = _FakeTensorModeSerializer(fake_mode)
513
+
514
+ from pickle import PicklingError
515
+
516
+ try:
517
+ input = _WireProtocolInput(
518
+ gm,
519
+ example_inputs,
520
+ inputs_to_check,
521
+ graph_kwargs,
522
+ context,
523
+ config.save_config_portable(),
524
+ _VirtualizedSerializer.serialize(),
525
+ deterministic_guard_for_testing,
526
+ logger_state,
527
+ lowering,
528
+ fake_tensor_mode,
529
+ ).serialize()
530
+ return (input, constants)
531
+ except (AttributeError, BypassFxGraphCache, PicklingError):
532
+ # For example: AttributeError: Can't pickle local object
533
+ # 'make_opaque_unary_fn.<locals>.OpaqueUnaryFn'
534
+
535
+ # TODO: scuba record about not being able to do this?
536
+ log.warning("Unable to pickle input graph or example inputs", exc_info=True)
537
+
538
+ return None
539
+
540
+ @abstractmethod
541
+ def _send_to_child(
542
+ self, pickled_input: _WireProtocolPickledInput
543
+ ) -> _WireProtocolPickledOutput:
544
+ # The implementation of this should transfer `input` to the child, call
545
+ # `_run_in_child(input)` and transfer the result back.
546
+ ...
547
+
548
+ def _postprocess(self, output: _WireProtocolOutput) -> None:
549
+ pass
550
+
551
+ @classmethod
552
+ def _run_in_child(
553
+ cls,
554
+ pickled_input: _WireProtocolPickledInput,
555
+ extra_env: Mapping[str, str | None] | None = None,
556
+ ) -> _WireProtocolPickledOutput:
557
+ metrics = CachedMetricsHelper()
558
+
559
+ with contextlib.ExitStack() as stack:
560
+ stack.enter_context(patch_subprocess_env(extra_env))
561
+
562
+ # Save warnings to "replay" in the parent
563
+ warning_replay = stack.enter_context(warnings.catch_warnings(record=True))
564
+
565
+ # TODO: Should we split the input into multiple sections where each
566
+ # section sets up state for the previous section? (i.e. a Config section
567
+ # which we decode and apply, followed by a FakeTensorMode section which
568
+ # we decode and apply, etc)
569
+ input = pickled_input.deserialize()
570
+
571
+ stack.enter_context(input.virtualized.patch())
572
+ stack.enter_context(input.lowering.patch())
573
+ stack.enter_context(config.patch(input.config))
574
+ captured_logs = stack.enter_context(input.logger_state)
575
+ if input.deterministic_guard_for_testing:
576
+ stack.enter_context(input.deterministic_guard_for_testing)
577
+ stack.enter_context(torch._guards.tracing(input.tracing_context))
578
+ stack.enter_context(DebugContext())
579
+
580
+ fake_mode = _current_fake_mode()
581
+ stack.enter_context(input.fake_tensor_mode.patch(fake_mode))
582
+
583
+ output_graph = _InProcessFxCompile().codegen_and_compile(
584
+ input.gm,
585
+ input.example_inputs,
586
+ input.inputs_to_check,
587
+ input.graph_kwargs,
588
+ )
589
+
590
+ logs = captured_logs.finish()
591
+
592
+ return _WireProtocolOutput(
593
+ output_graph,
594
+ metrics.get_deltas(),
595
+ logs,
596
+ warning_replay,
597
+ fake_mode.shape_env,
598
+ ).serialize()
599
+
600
+
601
+ # This is a debugging/testing implementation of FxCompile which serializes the
602
+ # input and output but still runs the FxCompile in-process.
603
+ @final
604
+ class _DebugSerdeFxCompile(_SerializedFxCompile):
605
+ @override
606
+ def _send_to_child(
607
+ self, pickled_input: _WireProtocolPickledInput
608
+ ) -> _WireProtocolPickledOutput:
609
+ # For debugging just serde the input and output but don't run in a
610
+ # subprocess.
611
+ return self._run_in_child(pickled_input)
612
+
613
+
614
+ class _OutOfProcessFxCompile(_SerializedFxCompile):
615
+ """
616
+ Represents an FxCompile which is run outside the current process (in
617
+ either a subprocess or possibly even a separate machine).
618
+ """
619
+
620
+ @override
621
+ @final
622
+ def _send_to_child(
623
+ self, pickled_input: _WireProtocolPickledInput
624
+ ) -> _WireProtocolPickledOutput:
625
+ f = self._send_to_child_async(pickled_input)
626
+
627
+ # For debugging: If we want to print status updates...
628
+ # last = time.time()
629
+ # while not f.done():
630
+ # print("tick...")
631
+ # time.sleep(0.125)
632
+ # now = time.time()
633
+ # if now - last > 1:
634
+ # last = now
635
+
636
+ return f.result()
637
+
638
+ @abstractmethod
639
+ def _send_to_child_async(
640
+ self, pickled_input: _WireProtocolPickledInput
641
+ ) -> Future[_WireProtocolPickledOutput]: ...
642
+
643
+ def _postprocess(self, output: _WireProtocolOutput) -> None:
644
+ # Since our metrics were gathered in a subprocess make sure to add them
645
+ # here.
646
+ CachedMetricsHelper.apply_deltas(output.metrics)
647
+
648
+ # This is used by tests to check the output for specific details. For
649
+ # remote things (subproc and RE) we need to do the `save_output_code`
650
+ # here since it didn't happen earlier in-process. In the future if this
651
+ # doesn't have "source_code" (it's a CompiledAOTI, for example) and we
652
+ # need it we'll have to grab it and serialize it separately from the
653
+ # child.
654
+ if GraphLowering.save_output_code is not None:
655
+ GraphLowering.save_output_code(output.graph.source_code) # type: ignore[attr-defined]
656
+
657
+ # And forward our collected logs. The cache is cleared when the outer
658
+ # function exits.
659
+ @functools.cache
660
+ def getLogger(name: str) -> logging.Logger:
661
+ return logging.getLogger(name)
662
+
663
+ if output.warning_replay:
664
+ for w in output.warning_replay:
665
+ warnings.warn_explicit(
666
+ message=w.message,
667
+ category=w.category,
668
+ filename=w.filename,
669
+ lineno=w.lineno,
670
+ source=w.source,
671
+ )
672
+
673
+ for record in output.logs:
674
+ logger = getLogger(record.name)
675
+ logger.handle(record)
676
+
677
+
678
+ # For debugging - create a _FxCompile which writes the serialized data to a file
679
+ # and then exits.
680
+ #
681
+ # TODO: make this a FxCompileMode value?
682
+ #
683
+ # The "child runner" should look something like this:
684
+ #
685
+ # import torch
686
+ # from torch._inductor import compile_fx
687
+ # idx = 0
688
+ # with open(f"/tmp/pytorch_compile_fx_tmp_input_{idx}.bin", "rb") as f:
689
+ # input = compile_fx._WireProtocolPickledInput(f.read())
690
+ # result = compile_fx._SubprocessFxCompile._run_in_child(input)
691
+ # with open(f"/tmp/pytorch_compile_fx_tmp_output_{idx}.bin", "wb") as f:
692
+ # f.write(result.value)
693
+ #
694
+ @final
695
+ class _DebugFileFxCompile(_SerializedFxCompile):
696
+ file_index = 0
697
+
698
+ @override
699
+ def _send_to_child(
700
+ self, pickled_input: _WireProtocolPickledInput
701
+ ) -> _WireProtocolPickledOutput:
702
+ idx = _DebugFileFxCompile.file_index
703
+ _DebugFileFxCompile.file_index += 1
704
+
705
+ name = os.path.join(
706
+ tempfile.gettempdir(), f"pytorch_compile_fx_tmp_input_{idx}.bin"
707
+ )
708
+ with open(name, "wb") as f:
709
+ f.write(pickled_input.value)
710
+ print(f"Wrote to {name}")
711
+
712
+ if False:
713
+ name = os.path.join(
714
+ tempfile.gettempdir(), f"pytorch_compile_fx_tmp_actual_{idx}.bin"
715
+ )
716
+ actual = self._run_in_child(pickled_input)
717
+ with open(name, "wb") as f:
718
+ f.write(actual.value)
719
+ return actual
720
+ elif False:
721
+ name = os.path.join(
722
+ tempfile.gettempdir(), f"pytorch_compile_fx_tmp_output_{idx}.bin"
723
+ )
724
+ with open(name, "rb") as f:
725
+ result = _WireProtocolPickledOutput(f.read())
726
+ print(f"Read from {name}")
727
+ return result
728
+ else:
729
+ os._exit(-1)
.venv/lib/python3.12/site-packages/torch/_inductor/compile_fx_subproc.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import atexit
4
+ import functools
5
+ import os
6
+ from typing import TYPE_CHECKING
7
+ from typing_extensions import final, override
8
+
9
+ import torch._inductor.async_compile
10
+ import torch.fx
11
+ from torch._inductor.compile_worker.subproc_pool import (
12
+ AnyPool,
13
+ SubprocKind,
14
+ SubprocPool,
15
+ )
16
+ from torch._inductor.utils import clear_caches
17
+
18
+ from .compile_fx_ext import (
19
+ _OutOfProcessFxCompile,
20
+ _WireProtocolPickledInput,
21
+ _WireProtocolPickledOutput,
22
+ )
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ from collections.abc import Mapping
27
+ from concurrent.futures import Future
28
+
29
+
30
+ @final
31
+ class _SubprocessFxCompile(_OutOfProcessFxCompile):
32
+ @override
33
+ def _send_to_child_async(
34
+ self, input: _WireProtocolPickledInput
35
+ ) -> Future[_WireProtocolPickledOutput]:
36
+ # TODO: Do we need to copy across some kind of logging IDs? (ChromiumEventLogger)
37
+
38
+ pool = self.process_pool()
39
+
40
+ # TODO: This is probably the wrong thing to do long-term - but for now
41
+ # let's share the cache so we can identify tests broken by this later.
42
+ env_vars = ["TORCHINDUCTOR_CACHE_DIR", "TRITON_CACHE_DIR"]
43
+ extra_env = {v: os.environ.get(v) for v in env_vars}
44
+
45
+ return pool.submit(
46
+ _SubprocessFxCompile._run_in_child_subprocess, input, extra_env
47
+ )
48
+
49
+ @staticmethod
50
+ @functools.cache
51
+ def process_pool() -> AnyPool:
52
+ pool = SubprocPool(
53
+ # TODO: Consider raising this limit if we start using async w/
54
+ # subprocess and want to compile multiple graphs in parallel.
55
+ 1,
56
+ kind=SubprocKind.SPAWN,
57
+ )
58
+
59
+ atexit.register(pool.shutdown)
60
+
61
+ return pool
62
+
63
+ @classmethod
64
+ def _run_in_child_subprocess(
65
+ cls,
66
+ pickled_input: _WireProtocolPickledInput,
67
+ extra_env: Mapping[str, str | None] | None,
68
+ ) -> _WireProtocolPickledOutput:
69
+ # TODO: In subprocess mode we need to clear the inductor caches.
70
+ # The problem:
71
+ # 1. We compile in worker A which fills stuff in tmpdir
72
+ # 2. parent clears inductor caches which deletes tmpdirs and tells
73
+ # cpp_prefix_path() to clear its LRU cache
74
+ # 3. We compile a second time in subproc A - but since we never told
75
+ # cpp_prefix_path() in worker A to clear its LRU it thinks the
76
+ # tmpdir still exists and fails to compile.
77
+ #
78
+ # TODO: We probably should be using a separate tmpdir in the worker
79
+ # anyway... but we should probably still respect clear_caches()
80
+ # in the parent... maybe?
81
+ #
82
+ # TODO: We could be less aggressive by keeping a clock which gets
83
+ # incremented when we clear the cache, send the clock to the worker and
84
+ # only clear caches if the clock changed since last time.
85
+ #
86
+ clear_caches()
87
+ torch._inductor.metrics.reset()
88
+
89
+ # TODO: turn off config.fx_graph_async_compile
90
+
91
+ result = cls._run_in_child(pickled_input, extra_env)
92
+ return result
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__init__.py ADDED
File without changes
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__main__.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ if triton is None:
33
+ raise AssertionError("triton failed to preload in parent")
34
+ except ImportError:
35
+ pass
36
+
37
+
38
+ def _lookup_and_create_type(base: type[_T], qname: str) -> _T:
39
+ """
40
+ Given a base type and qualified name: import & lookup that name, check
41
+ that it's of the given type and then instantiate it.
42
+ """
43
+ pkg, name = qname.rsplit(".", 1)
44
+ mod = importlib.import_module(pkg)
45
+ ty = getattr(mod, name)
46
+ if not issubclass(ty, base):
47
+ raise TypeError(f"Type {ty} is not a subtype of {base}")
48
+ return ty()
49
+
50
+
51
+ def main():
52
+ try:
53
+ parser = argparse.ArgumentParser()
54
+ parser.add_argument(
55
+ "--pickler", type=functools.partial(_lookup_and_create_type, SubprocPickler)
56
+ )
57
+ parser.add_argument("--kind", type=SubprocKind)
58
+ parser.add_argument("--workers", type=int)
59
+ parser.add_argument("--parent", type=int)
60
+ parser.add_argument("--read-fd", type=int)
61
+ parser.add_argument("--write-fd", type=int)
62
+ parser.add_argument("--torch-key", type=str)
63
+ args = parser.parse_args()
64
+ if os.getppid() != args.parent:
65
+ sys.exit(0)
66
+ read_fd = os.fdopen(args.read_fd, "rb")
67
+ write_fd = os.fdopen(args.write_fd, "wb")
68
+
69
+ pre_fork_setup()
70
+
71
+ torch_key.set(base64.b64decode(args.torch_key.encode("utf-8"))) # type: ignore[attr-defined]
72
+
73
+ _async_compile_initializer(args.parent)
74
+
75
+ SubprocMain(args.pickler, args.kind, args.workers, read_fd, write_fd).main()
76
+ except Exception:
77
+ log.exception("Uncaught exception in compile_worker subprocess")
78
+
79
+
80
+ if __name__ == "__main__":
81
+ main()
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (205 Bytes). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/__main__.cpython-312.pyc ADDED
Binary file (3.92 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/subproc_pool.cpython-312.pyc ADDED
Binary file (40.2 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/timer.cpython-312.pyc ADDED
Binary file (2.71 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/tracked_process_pool.cpython-312.pyc ADDED
Binary file (6.15 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/utils.cpython-312.pyc ADDED
Binary file (2.27 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/__pycache__/watchdog.cpython-312.pyc ADDED
Binary file (6.86 kB). View file
 
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/subproc_pool.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import functools
3
+ import itertools
4
+ import json
5
+ import logging
6
+ import multiprocessing
7
+ import os
8
+ import pickle
9
+ import struct
10
+ import subprocess
11
+ import sys
12
+ import threading
13
+ import time
14
+ import traceback
15
+ import typing
16
+ from collections.abc import Callable
17
+ from concurrent.futures import Future, ProcessPoolExecutor
18
+ from concurrent.futures.process import BrokenProcessPool
19
+ from enum import Enum, IntEnum
20
+ from pathlib import Path
21
+ from typing import Any, IO, TypeVar
22
+ from typing_extensions import Never, ParamSpec
23
+
24
+ # _thread_safe_fork is needed because the subprocesses in the pool can read
25
+ # justknobs, e.g., in the Triton compiler. For internal, the import installs
26
+ # functionality to destroy singletons before forking and re-enable them after.
27
+ import torch._thread_safe_fork # noqa: F401
28
+ from torch._inductor import config
29
+ from torch._inductor.codecache import torch_key
30
+ from torch._inductor.compile_worker import watchdog
31
+ from torch._inductor.compile_worker.timer import Timer
32
+ from torch._inductor.compile_worker.tracked_process_pool import (
33
+ TrackedProcessPoolExecutor,
34
+ )
35
+ from torch._inductor.compile_worker.utils import _async_compile_initializer
36
+ from torch._inductor.utils import get_ld_library_path, python_subprocess_env
37
+ from torch._logging import trace_structured
38
+ from torch._utils_internal import find_compile_subproc_binary
39
+ from torch.monitor import _WaitCounter, _WaitCounterTracker
40
+
41
+
42
+ log = logging.getLogger(__name__)
43
+
44
+ _P = ParamSpec("_P")
45
+ _T = TypeVar("_T")
46
+
47
+
48
+ class MsgHeader(IntEnum):
49
+ ERROR = 0
50
+ SHUTDOWN = 1
51
+ QUIESCE = 2
52
+ WAKEUP = 3
53
+ JOB = 4
54
+ # Sidecar -> parent watchdog report about a still-running job (out-of-band,
55
+ # low volume). Payload is a pickled status dict; does not affect the future.
56
+ STATUS = 5
57
+
58
+
59
+ def _current_compile_id() -> Any:
60
+ # Snapshotted at submit so a later watchdog STATUS report (handled on the
61
+ # read thread, which has no ambient compile context) can be attributed to the
62
+ # right compile in tlparse.
63
+ try:
64
+ from torch._guards import CompileContext
65
+
66
+ return CompileContext.current_compile_id()
67
+ except Exception:
68
+ return None
69
+
70
+
71
+ def _pack_msg(msg_header: MsgHeader, job_id: int, length: int) -> bytes:
72
+ return struct.pack("nnn", int(msg_header), job_id, length)
73
+
74
+
75
+ def _unpack_msg(data: bytes) -> tuple[MsgHeader, int, int]:
76
+ if not data:
77
+ return MsgHeader.ERROR, -1, -1
78
+ msg_header, job_id, length = struct.unpack("nnn", data)
79
+ return MsgHeader(msg_header), job_id, length
80
+
81
+
82
+ msg_bytes = len(_pack_msg(MsgHeader.JOB, 0, 0))
83
+
84
+ # How often the parent polls the sidecar process for liveness. The sidecar
85
+ # dying is the only signal this catches, so a coarse interval is fine.
86
+ _SIDECAR_HEALTH_POLL_SECONDS = 2.0
87
+
88
+ # How long, in total, to let compile workers exit on SIGTERM during pool
89
+ # teardown before escalating to SIGKILL. A worker wedged holding a lock or in a
90
+ # C/GIL section won't honor SIGTERM, and an unbounded wait for it would stall the
91
+ # whole shutdown.
92
+ _WORKER_TERMINATE_GRACE_SECONDS = 10.0
93
+
94
+
95
+ def _send_msg(
96
+ write_pipe: IO[bytes], msg_header: MsgHeader, job_id: int = -1, data: bytes = b""
97
+ ) -> None:
98
+ length = len(data)
99
+ write_pipe.write(_pack_msg(msg_header, job_id, length))
100
+ if length > 0:
101
+ write_pipe.write(data)
102
+ write_pipe.flush()
103
+
104
+
105
+ def _recv_msg(read_pipe: IO[bytes]) -> tuple[MsgHeader, int, bytes]:
106
+ msg_header, job_id, length = _unpack_msg(read_pipe.read(msg_bytes))
107
+ data = read_pipe.read(length) if length > 0 else b""
108
+ return msg_header, job_id, data
109
+
110
+
111
+ class _SubprocExceptionInfo:
112
+ """
113
+ Carries exception info from subprocesses across the wire. traceback
114
+ objects are not pickleable, so we store the trace as a string and
115
+ use it for the message in the exception thrown in the main process.
116
+ """
117
+
118
+ def __init__(self, details: str) -> None:
119
+ self.details = details
120
+
121
+
122
+ class SubprocException(Exception):
123
+ """
124
+ Thrown when a job in a subprocess raises an Exception.
125
+ """
126
+
127
+ def __init__(self, details: str, name: str = "<unknown>") -> None:
128
+ self.details = details
129
+ super().__init__(
130
+ f"An exception occurred in a subprocess:\n\nName={name}\n{details}"
131
+ )
132
+
133
+ def with_name(self, name: str) -> "SubprocException":
134
+ return SubprocException(self.details, name)
135
+
136
+
137
+ class SubprocPickler:
138
+ """
139
+ Allows a caller to provide a custom pickler for passing data with the
140
+ subprocess.
141
+ """
142
+
143
+ def dumps(self, obj: object) -> bytes:
144
+ return pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
145
+
146
+ def loads(self, data: bytes) -> object:
147
+ return pickle.loads(data)
148
+
149
+
150
+ class SubprocKind(Enum):
151
+ FORK = "fork"
152
+ SPAWN = "spawn"
153
+
154
+
155
+ class SubprocPool:
156
+ """
157
+ Mimic a concurrent.futures.ProcessPoolExecutor, but wrap it in
158
+ a subprocess.Popen() to try to avoid issues with forking/spawning
159
+ """
160
+
161
+ def __init__(
162
+ self,
163
+ nprocs: int,
164
+ pickler: SubprocPickler | None = None,
165
+ kind: SubprocKind = SubprocKind.FORK,
166
+ quiesce: bool = False,
167
+ ) -> None:
168
+ entry = os.path.join(os.path.dirname(__file__), "__main__.py")
169
+ self.pickler = pickler or SubprocPickler()
170
+ self.kind = kind
171
+
172
+ subproc_read_fd, write_fd = os.pipe()
173
+ read_fd, subproc_write_fd = os.pipe()
174
+ self.write_pipe = os.fdopen(write_fd, "wb")
175
+ self.read_pipe = os.fdopen(read_fd, "rb")
176
+ torch_key_str = base64.b64encode(torch_key()).decode("utf-8")
177
+
178
+ cmd = [
179
+ sys.executable,
180
+ entry,
181
+ ]
182
+ if (binary := find_compile_subproc_binary()) is not None:
183
+ cmd = [binary]
184
+
185
+ args = [
186
+ f"--pickler={self.pickler.__class__.__module__}.{self.pickler.__class__.__name__}",
187
+ f"--kind={self.kind.value}",
188
+ f"--workers={nprocs}",
189
+ f"--parent={os.getpid()}",
190
+ f"--read-fd={str(subproc_read_fd)}",
191
+ f"--write-fd={str(subproc_write_fd)}",
192
+ f"--torch-key={torch_key_str}",
193
+ ]
194
+ cmd.extend(args)
195
+ log_path = None
196
+ self.log_file = None
197
+
198
+ if config.worker_suppress_logging:
199
+ log_path = os.devnull
200
+ log.info("Suppressing compile worker output due to config")
201
+ else:
202
+ log_path = config.torchinductor_worker_logpath
203
+ if not log_path:
204
+ log_path = config.get_worker_log_path()
205
+
206
+ if log_path:
207
+ # pyrefly: ignore [bad-assignment]
208
+ self.log_file = open(log_path, "w") # noqa:SIM115
209
+ # Kept so the liveness watchdog can tail worker output if the sidecar dies.
210
+ self.log_path = log_path
211
+
212
+ self.process = subprocess.Popen(
213
+ cmd,
214
+ env={
215
+ **python_subprocess_env(),
216
+ # Safeguard against creating a SubprocPool in the subprocess.
217
+ "TORCH_WARM_POOL": "0",
218
+ # Some internal usages need a modified LD_LIBRARY_PATH.
219
+ "LD_LIBRARY_PATH": get_ld_library_path(),
220
+ },
221
+ pass_fds=(subproc_read_fd, subproc_write_fd),
222
+ stdout=self.log_file,
223
+ stderr=self.log_file,
224
+ )
225
+ # The sidecar inherited these via pass_fds; the parent uses its own ends
226
+ # (write_pipe/read_pipe) and must drop its copies. Otherwise the parent
227
+ # itself keeps the result pipe's write end open, so read_pipe would never
228
+ # EOF even after the sidecar and all workers are gone.
229
+ os.close(subproc_read_fd)
230
+ os.close(subproc_write_fd)
231
+
232
+ self.write_lock = threading.Lock()
233
+ self.read_thread = threading.Thread(
234
+ target=self._read_thread, name="InductorSubproc", daemon=True
235
+ )
236
+ # Backstop for the sidecar dying. Closing the inherited pipe fds (in the
237
+ # parent above and in each worker's initializer) means a dead sidecar
238
+ # normally yields a clean EOF that _read_thread handles. This watchdog
239
+ # covers the cases where EOF does not arrive -- e.g. a stray fd copy still
240
+ # holding the write end open -- by detecting the dead process directly.
241
+ self.health_thread = threading.Thread(
242
+ target=self._health_monitor, name="InductorSubprocHealth", daemon=True
243
+ )
244
+
245
+ self.futures_lock = threading.Lock()
246
+ self.pending_futures: dict[int, Future[Any]] = {}
247
+ # Compile id captured at submit so watchdog STATUS reports (handled on the
248
+ # read thread) attribute to the right compile in tlparse. Keyed by job_id.
249
+ self._job_compile_id: dict[int, Any] = {}
250
+ # The pending waitcounter, is used to indicate the time when we have any specific job running.
251
+ self.pending_waitcounters: dict[int, Any] = {}
252
+ self.job_id_count = itertools.count()
253
+
254
+ # The running waitcounter indicates the time when the SubProcPool object exists.
255
+ self.running = True
256
+ self.running_waitcounter = _WaitCounter(
257
+ "pytorch.wait_counter.subproc_pool.running"
258
+ ).guard()
259
+ self.running_waitcounter.__enter__()
260
+
261
+ # The quiesce waitcounter indicates when the job is in a quiesced state.
262
+ self.quiesce_waitcounter: _WaitCounterTracker | None = None
263
+
264
+ # Firstjob is used to capture the time from when the firstjob is queued, to when the first job is done.
265
+ self.firstjob = True
266
+ self.firstjob_id: int | None = None
267
+ self.firstjob_waitcounter = _WaitCounter(
268
+ "pytorch.wait_counter.subproc_pool.first_job"
269
+ ).guard()
270
+
271
+ if quiesce:
272
+ self.timer: Timer | None = Timer(
273
+ config.quiesce_async_compile_time, self.quiesce
274
+ )
275
+ else:
276
+ self.timer = None
277
+
278
+ # Start threads last to ensure all member variables are initialized
279
+ # before any access.
280
+ self.read_thread.start()
281
+ self.health_thread.start()
282
+
283
+ def submit(
284
+ self, job_fn: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs
285
+ ) -> Future[_T]:
286
+ if args or kwargs:
287
+ # pyrefly: ignore [bad-assignment]
288
+ job_fn = functools.partial(job_fn, *args, **kwargs)
289
+ job_data = self.pickler.dumps(job_fn)
290
+ future: Future[_T]
291
+ with self.futures_lock:
292
+ job_id = next(self.job_id_count)
293
+ self.pending_futures[job_id] = future = Future()
294
+ self._job_compile_id[job_id] = _current_compile_id()
295
+ self.pending_waitcounters[job_id] = _WaitCounter(
296
+ "pytorch.wait_counter.subproc_pool.job"
297
+ ).guard()
298
+ self.pending_waitcounters[job_id].__enter__()
299
+ if self.quiesce_waitcounter:
300
+ self.firstjob = True
301
+ self.quiesce_waitcounter.__exit__()
302
+ self.quiesce_waitcounter = None
303
+ # This can be entered from either quiesce wakeup, or from startup.
304
+ if self.firstjob:
305
+ self.firstjob_id = job_id
306
+ self.firstjob_waitcounter.__enter__()
307
+ self.firstjob = False
308
+ future.set_running_or_notify_cancel()
309
+ self._send(MsgHeader.JOB, job_id, job_data)
310
+ return future
311
+
312
+ def _send(self, msg_header: MsgHeader, job_id: int = -1, data: bytes = b"") -> None:
313
+ with self.write_lock:
314
+ if not self.running:
315
+ raise RuntimeError("Attempting to use a closed pool")
316
+ _send_msg(self.write_pipe, msg_header, job_id, data)
317
+
318
+ def _read_thread(self) -> None:
319
+ while True:
320
+ data = b""
321
+ job_id = -1
322
+ try:
323
+ msg_header, job_id, data = _recv_msg(self.read_pipe)
324
+ except Exception:
325
+ # Something went wrong during the read. There's no way we have a
326
+ # valid msg.
327
+ log.exception("failure in subproc_pool._recv_msg")
328
+ msg_header = MsgHeader.ERROR
329
+
330
+ if msg_header == MsgHeader.STATUS:
331
+ # Out-of-band watchdog report; does not touch futures.
332
+ self._handle_worker_status(job_id, data)
333
+ continue
334
+
335
+ if msg_header != MsgHeader.JOB:
336
+ # read_pipe returned None or got exception
337
+ if self.running:
338
+ log.warning("SubprocPool unclean exit")
339
+ self.running = False
340
+ self.running_waitcounter.__exit__()
341
+ self.read_pipe.close()
342
+ # Cancel all the pending futures.
343
+ self.shutdown()
344
+ return
345
+
346
+ try:
347
+ result = self.pickler.loads(data)
348
+ except Exception as e:
349
+ # Something went wrong unpickling. We have a job_id so just
350
+ # notify that particular future and continue on.
351
+ log.exception("unpickle failure in SubprocPool._read_thread")
352
+ result = e
353
+
354
+ with self.futures_lock:
355
+ if not self.running:
356
+ return
357
+ if self.timer:
358
+ self.timer.record_call()
359
+ if isinstance(result, _SubprocExceptionInfo):
360
+ # An exception occurred in the submitted job
361
+ self.pending_futures[job_id].set_exception(
362
+ SubprocException(result.details)
363
+ )
364
+ elif isinstance(result, Exception):
365
+ # An exception occurred in some of our subprocess machinery.
366
+ self.pending_futures[job_id].set_exception(result)
367
+ else:
368
+ self.pending_futures[job_id].set_result(result)
369
+
370
+ self.pending_waitcounters[job_id].__exit__()
371
+ del self.pending_waitcounters[job_id]
372
+ if self.firstjob_id == job_id:
373
+ self.firstjob_waitcounter.__exit__()
374
+
375
+ del self.pending_futures[job_id]
376
+ self._job_compile_id.pop(job_id, None)
377
+
378
+ def _health_monitor(self) -> None:
379
+ # Poll the sidecar for liveness. If it dies while we still think we are
380
+ # running, fail the pending compiles rather than let waiters block
381
+ # forever (see health_thread comment in __init__).
382
+ while self.running:
383
+ returncode = self.process.poll()
384
+ if returncode is not None:
385
+ self._on_sidecar_death(returncode)
386
+ return
387
+ time.sleep(_SIDECAR_HEALTH_POLL_SECONDS)
388
+
389
+ def _on_sidecar_death(self, returncode: int) -> None:
390
+ with self.futures_lock:
391
+ if not self.running:
392
+ # Expected exit (shutdown) or already handled.
393
+ return
394
+ self.running = False
395
+ # `running` is set under different locks across shutdown()/_read_thread/
396
+ # here, so this exit can race another for the same transition. That's
397
+ # safe: _WaitCounterTracker.__exit__ is idempotent (optional::reset()).
398
+ self.running_waitcounter.__exit__()
399
+
400
+ pid = self.process.pid
401
+ log.error(
402
+ "Inductor compile worker sidecar (pid %s) exited unexpectedly with "
403
+ "code %s during compilation; failing pending compile jobs. Re-run "
404
+ "with TORCHINDUCTOR_COMPILE_THREADS=1 to compile in the main process.",
405
+ pid,
406
+ returncode,
407
+ )
408
+ self._log_sidecar_death_diagnostics(returncode)
409
+
410
+ exc = RuntimeError(
411
+ f"Inductor compile worker sidecar (pid {pid}) exited unexpectedly "
412
+ f"with code {returncode} during compilation. Re-run with "
413
+ "TORCHINDUCTOR_COMPILE_THREADS=1 to compile in the main process."
414
+ )
415
+ with self.futures_lock:
416
+ for job_id, future in self.pending_futures.items():
417
+ if not future.cancel():
418
+ future.set_exception(exc)
419
+ waitcounter = self.pending_waitcounters.pop(job_id, None)
420
+ if waitcounter is not None:
421
+ waitcounter.__exit__()
422
+ self.pending_futures.clear()
423
+ self._job_compile_id.clear()
424
+ # We intentionally do not close read_pipe here. _read_thread owns it and
425
+ # may be mid-read; closing a buffered pipe out from under a concurrent
426
+ # read can deadlock on the buffer lock. It is a daemon thread, so leaving
427
+ # it is harmless now that the futures are resolved -- and if the sidecar's
428
+ # death already produced an EOF, _read_thread will close the pipe itself.
429
+
430
+ def _log_sidecar_death_diagnostics(self, returncode: int) -> None:
431
+ tail = ""
432
+ if self.log_path and self.log_path != os.devnull:
433
+ try:
434
+ with open(self.log_path, errors="replace") as f:
435
+ tail = "".join(f.readlines()[-50:])
436
+ except OSError:
437
+ pass
438
+ if tail:
439
+ log.error(
440
+ "Last output from compile worker sidecar (pid %s):\n%s",
441
+ self.process.pid,
442
+ tail,
443
+ )
444
+ # Surface the same info to structured tracing so production jobs (which
445
+ # only have tlparse access) can diagnose the crash.
446
+ try:
447
+ trace_structured(
448
+ "artifact",
449
+ metadata_fn=lambda: {
450
+ "name": "compile_worker_sidecar_death",
451
+ "encoding": "string",
452
+ },
453
+ payload_fn=lambda: (
454
+ f"sidecar pid={self.process.pid} returncode={returncode}\n\n{tail}"
455
+ ),
456
+ )
457
+ except Exception:
458
+ log.warning("Failed to emit sidecar-death trace artifact", exc_info=True)
459
+
460
+ def _handle_worker_status(self, job_id: int, data: bytes) -> None:
461
+ # Best-effort, and runs on the read thread: a bad status report (corrupt
462
+ # payload or a logging failure) must not escape and kill result
463
+ # processing, so guard the whole thing.
464
+ try:
465
+ status = self.pickler.loads(data)
466
+ if not isinstance(status, dict):
467
+ return
468
+ compile_id = self._job_compile_id.get(job_id)
469
+ record = {**status, "compile_id": str(compile_id) if compile_id else None}
470
+ trace_structured(
471
+ "artifact",
472
+ metadata_fn=lambda: {
473
+ "name": "compile_worker_status",
474
+ "encoding": "json",
475
+ },
476
+ payload_fn=lambda: json.dumps(record),
477
+ compile_id=compile_id,
478
+ expect_trace_id=False,
479
+ suppress_context=True,
480
+ record_logging_overhead=False,
481
+ )
482
+ except Exception:
483
+ log.warning("failed to report compile worker status", exc_info=True)
484
+
485
+ def quiesce(self) -> None:
486
+ self._send(MsgHeader.QUIESCE)
487
+ if self.quiesce_waitcounter is None:
488
+ self.quiesce_waitcounter = _WaitCounter(
489
+ "pytorch.wait_counter.subproc_pool.quiesced"
490
+ ).guard()
491
+ self.quiesce_waitcounter.__enter__()
492
+
493
+ def wakeup(self) -> None:
494
+ self._send(MsgHeader.WAKEUP)
495
+
496
+ def shutdown(self) -> None:
497
+ try:
498
+ with self.write_lock:
499
+ if not self.running:
500
+ return
501
+ if self.timer:
502
+ self.timer.quit()
503
+ self.running = False
504
+ self.running_waitcounter.__exit__()
505
+ _send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
506
+ self.write_pipe.close()
507
+ try:
508
+ self.process.wait(300)
509
+ except subprocess.TimeoutExpired:
510
+ # The sidecar did not exit in time (e.g. wedged tearing down its
511
+ # own worker pool). Don't stall the whole process; kill it and
512
+ # move on. TimeoutExpired is not an OSError, so it would
513
+ # otherwise propagate uncaught out of shutdown().
514
+ log.warning(
515
+ "Compile worker sidecar (pid %s) did not exit within 300s; "
516
+ "killing it.",
517
+ self.process.pid,
518
+ )
519
+ self.process.kill()
520
+ self.process.wait()
521
+ if self.log_file:
522
+ self.log_file.close()
523
+ except OSError:
524
+ log.warning("Ignored OSError in pool shutdown", exc_info=True)
525
+ finally:
526
+ with self.futures_lock:
527
+ for future in self.pending_futures.values():
528
+ if not future.cancel():
529
+ future.set_exception(RuntimeError("SubprocPool closed"))
530
+ self.pending_futures.clear()
531
+ self._job_compile_id.clear()
532
+
533
+
534
+ class SubprocMain:
535
+ """Communicates with a SubprocPool in the parent process, called by __main__.py"""
536
+
537
+ def __init__(
538
+ self,
539
+ pickler: SubprocPickler,
540
+ kind: SubprocKind,
541
+ nprocs: int,
542
+ read_pipe: IO[bytes],
543
+ write_pipe: IO[bytes],
544
+ ) -> None:
545
+ self.pickler = pickler
546
+ self.kind = kind
547
+ self.read_pipe = read_pipe
548
+ self.write_pipe = write_pipe
549
+ self.write_lock = threading.Lock()
550
+ self.nprocs = nprocs
551
+ self.pool: ProcessPoolExecutor | None = None
552
+ self.pool_finalizer: Any | None = None
553
+ self.running = True
554
+ # job_id -> monotonic submit time; scanned by the watchdog thread.
555
+ self._inflight: dict[int, float] = {}
556
+ self._inflight_lock = threading.Lock()
557
+ self._watchdog_stop = threading.Event()
558
+
559
+ def main(self) -> None:
560
+ # Phase heartbeats rely on fork inheritance of the shared buffer; spawn
561
+ # workers get no buffer and degrade to duration-only reporting.
562
+ if self.kind == SubprocKind.FORK:
563
+ watchdog.create(self.nprocs)
564
+ self._start_watchdog()
565
+ while True:
566
+ msg_header, job_id, data = _recv_msg(self.read_pipe)
567
+ if msg_header == MsgHeader.JOB:
568
+ self.submit(job_id, data)
569
+ elif msg_header == MsgHeader.WAKEUP:
570
+ self._start_pool()
571
+ elif msg_header == MsgHeader.QUIESCE:
572
+ self._quiesce()
573
+ else:
574
+ return self._shutdown()
575
+
576
+ def _quiesce(self) -> None:
577
+ self._shutdown_pool(terminate_workers=False)
578
+
579
+ def _shutdown(self) -> None:
580
+ self._watchdog_stop.set()
581
+ with self.write_lock:
582
+ self.running = False
583
+ try:
584
+ _send_msg(self.write_pipe, MsgHeader.SHUTDOWN)
585
+ self.write_pipe.close()
586
+ except BrokenPipeError:
587
+ pass # parent process already shutdown
588
+ self.read_pipe.close()
589
+ self._shutdown_pool(terminate_workers=True)
590
+
591
+ def _shutdown_pool(self, *, terminate_workers: bool) -> None:
592
+ if self.pool is None:
593
+ return
594
+
595
+ pool = self.pool
596
+ self.pool = None
597
+
598
+ if self.pool_finalizer is not None:
599
+ if terminate_workers:
600
+ self.pool_finalizer.cancel()
601
+ self.pool_finalizer = None
602
+
603
+ if terminate_workers:
604
+ # The sidecar is exiting, so do not let ProcessPoolExecutor's
605
+ # interpreter finalization wait for running compiler workers.
606
+ _terminate_process_pool(pool)
607
+ else:
608
+ pool.shutdown(wait=False)
609
+
610
+ def submit(self, job_id: int, data: bytes) -> None:
611
+ # Clock starts before _start_pool/_warm_process_pool, so the first job's
612
+ # reported elapsed intentionally includes cold pool creation and the fork
613
+ # of the workers -- that wait is real and worth surfacing.
614
+ with self._inflight_lock:
615
+ self._inflight[job_id] = time.monotonic()
616
+ while self.running:
617
+ try:
618
+ self._submit_inner(job_id, data)
619
+ return
620
+ except BrokenProcessPool:
621
+ # If any subprocess in the pool crashes, we get a BrokenProcessPool
622
+ # exception and the whole pool becomes unusable. Handle crashes by
623
+ # recreating the pool and resubmitting. Log it -- this was
624
+ # previously silent, hiding repeated worker crashes that can stall
625
+ # a job in this retry loop.
626
+ log.warning(
627
+ "Compile worker pool broke while submitting job %s; "
628
+ "recreating the pool and retrying.",
629
+ job_id,
630
+ exc_info=True,
631
+ )
632
+ self.pool = None
633
+
634
+ def _submit_inner(self, job_id: int, data: bytes) -> None:
635
+ def callback(fut: Future[Any]) -> None:
636
+ with self._inflight_lock:
637
+ self._inflight.pop(job_id, None)
638
+ if not self.running:
639
+ return
640
+ try:
641
+ result = fut.result()
642
+ except Exception as e:
643
+ log.exception("Error in subprocess")
644
+ result = self.pickler.dumps(e)
645
+ if not isinstance(result, bytes):
646
+ raise AssertionError(f"Expected bytes result, got {type(result)}")
647
+ with self.write_lock:
648
+ if self.running:
649
+ _send_msg(self.write_pipe, MsgHeader.JOB, job_id, result)
650
+ return
651
+
652
+ self._start_pool()
653
+ if self.pool is None:
654
+ raise AssertionError("pool must be initialized before submitting jobs")
655
+
656
+ future = self.pool.submit(
657
+ functools.partial(SubprocMain.do_job, self.pickler, job_id, data)
658
+ )
659
+ future.add_done_callback(callback)
660
+
661
+ def _start_pool(self) -> None:
662
+ if self.pool is not None:
663
+ return
664
+
665
+ # Recycle heartbeat slots before the new worker generation forks.
666
+ watchdog.reset()
667
+
668
+ # Only fork workers inherit the sidecar<->parent pipe fds and must close
669
+ # them (see _async_compile_initializer). Under spawn the workers do not
670
+ # inherit them (close_fds=True + O_CLOEXEC), and these integers would
671
+ # refer to unrelated fds the fresh interpreter reused -- closing them
672
+ # would be silent corruption, not a no-op.
673
+ close_fds = (
674
+ (self.read_pipe.fileno(), self.write_pipe.fileno())
675
+ if self.kind == SubprocKind.FORK
676
+ else ()
677
+ )
678
+ self.pool = TrackedProcessPoolExecutor(
679
+ self.nprocs,
680
+ mp_context=multiprocessing.get_context(self.kind.value),
681
+ initializer=functools.partial(
682
+ _async_compile_initializer, os.getpid(), close_fds
683
+ ),
684
+ )
685
+ self.pool_finalizer = multiprocessing.util.Finalize(
686
+ None, self.pool.shutdown, exitpriority=sys.maxsize
687
+ )
688
+ _warm_process_pool(self.pool, self.nprocs)
689
+
690
+ def _start_watchdog(self) -> None:
691
+ interval = config.compile_worker_watchdog_interval_seconds
692
+ if interval <= 0:
693
+ return
694
+ threading.Thread(
695
+ target=self._watchdog_loop,
696
+ args=(interval,),
697
+ name="InductorSubprocWatchdog",
698
+ daemon=True,
699
+ ).start()
700
+
701
+ def _watchdog_loop(self, interval: float) -> None:
702
+ # Every `interval` seconds, report any job still running past `interval`
703
+ # so a stuck/slow worker leaves a breadcrumb (the parent turns these into
704
+ # tlparse artifacts). Re-reports each tick with a growing elapsed time.
705
+ while not self._watchdog_stop.wait(interval):
706
+ now = time.monotonic()
707
+ now_ns = time.monotonic_ns()
708
+ heartbeats = watchdog.read_heartbeats()
709
+ with self._inflight_lock:
710
+ slow = [
711
+ (job_id, elapsed)
712
+ for job_id, start in self._inflight.items()
713
+ if (elapsed := now - start) >= interval
714
+ ]
715
+ for job_id, elapsed in slow:
716
+ self._report_status(job_id, elapsed, heartbeats.get(job_id), now_ns)
717
+
718
+ def _report_status(
719
+ self,
720
+ job_id: int,
721
+ elapsed: float,
722
+ heartbeat: tuple[int, int, int] | None,
723
+ now_ns: int,
724
+ ) -> None:
725
+ status: dict[str, Any] = {"job_id": job_id, "elapsed_s": round(elapsed, 1)}
726
+ if heartbeat is not None:
727
+ phase, phase_start_ns, worker_pid = heartbeat
728
+ status["phase"] = watchdog.Phase(phase).name.lower()
729
+ status["phase_elapsed_s"] = round((now_ns - phase_start_ns) / 1e9, 1)
730
+ status["worker_pid"] = worker_pid
731
+ elif watchdog.enabled():
732
+ # Heartbeats are active but this job isn't in any worker's slot. Almost
733
+ # always that means it's still queued in the pool -- a running (fork)
734
+ # worker stamps its slot before doing anything. It can also briefly
735
+ # mean the opposite: a job that just finished (clear_current_job ran in
736
+ # do_job's finally) but hasn't yet been popped from _inflight by the
737
+ # sidecar callback. That window is negligibly short, so we don't
738
+ # distinguish it.
739
+ status["phase"] = "queued"
740
+ # Otherwise phase tracking is unavailable (e.g. a spawn pool) and the
741
+ # report carries duration only -- we can't tell queued from running.
742
+ payload = self.pickler.dumps(status)
743
+ try:
744
+ with self.write_lock:
745
+ if self.running:
746
+ _send_msg(self.write_pipe, MsgHeader.STATUS, job_id, payload)
747
+ except (OSError, ValueError):
748
+ # Parent gone / pipe closed; the watchdog is best-effort.
749
+ pass
750
+
751
+ @staticmethod
752
+ def do_job(pickler: SubprocPickler, job_id: int, data: bytes) -> bytes:
753
+ # do the pickle/unpickle in the sub-subproc
754
+ watchdog.set_current_job(job_id)
755
+ try:
756
+ job = typing.cast(Callable[[], object], pickler.loads(data))
757
+ try:
758
+ result = job()
759
+ except Exception:
760
+ result = _SubprocExceptionInfo(traceback.format_exc())
761
+ return pickler.dumps(result)
762
+ finally:
763
+ watchdog.clear_current_job()
764
+
765
+
766
+ AnyPool = ProcessPoolExecutor | SubprocPool
767
+
768
+
769
+ def _get_process_pool_processes(pool: ProcessPoolExecutor) -> list[Any]:
770
+ processes = getattr(pool, "_processes", None)
771
+ if processes is not None:
772
+ return list(processes.values())
773
+
774
+ manager_thread = getattr(pool, "_executor_manager_thread", None)
775
+ manager_processes = getattr(manager_thread, "processes", None)
776
+ if manager_processes is not None:
777
+ return list(manager_processes.values())
778
+
779
+ return []
780
+
781
+
782
+ def _terminate_process_pool(pool: ProcessPoolExecutor) -> None:
783
+ processes = _get_process_pool_processes(pool)
784
+ for process in processes:
785
+ try:
786
+ if process.is_alive():
787
+ process.terminate()
788
+ except (OSError, ValueError):
789
+ log.warning("Ignored error terminating compile worker", exc_info=True)
790
+
791
+ # Give workers a bounded, shared grace period to exit on the SIGTERM above,
792
+ # then SIGKILL any that are wedged. Without this the pool.shutdown(wait=True)
793
+ # below can block on an unreaped worker until the parent's shutdown wait
794
+ # gives up (a ~300s stall).
795
+ deadline = time.time() + _WORKER_TERMINATE_GRACE_SECONDS
796
+ for process in processes:
797
+ try:
798
+ remaining = deadline - time.time()
799
+ if remaining > 0:
800
+ process.join(remaining)
801
+ if process.is_alive():
802
+ process.kill()
803
+ except (OSError, ValueError, AssertionError):
804
+ log.warning("Ignored error killing compile worker", exc_info=True)
805
+
806
+ try:
807
+ pool.shutdown(wait=True, cancel_futures=True)
808
+ except Exception:
809
+ log.warning("Ignored error shutting down compile worker pool", exc_info=True)
810
+
811
+
812
+ def _warm_process_pool(pool: ProcessPoolExecutor, n: int) -> None:
813
+ # We have to fork processes for compiler workers, but the more memory and other resources that are loaded, the
814
+ # slower the os.fork time is, quite drastically. It also holds the GIL so we can't put it on another thread.
815
+
816
+ # Examples:
817
+ # A simple x + x + x script: 10ms seconds in the middle of the program, 2ms at startup
818
+ # tf_efficientnet_b0 benchmark: 50ms! in the middle of the program , 3ms at startup
819
+
820
+ # So we want to start the workers early when it is still cheap, and also to allow the workers to get
821
+ # ready before we have work for them.
822
+
823
+ # ProcessPoolExecutor also does not launch the workers until it finds a point when all the workers are idle.
824
+ # But if we waited until then fork time will be long and we will be waiting for the processes to initialize.
825
+
826
+ # We force them to start here with some YOLOing of the internal methods.
827
+
828
+ if hasattr(pool, "_start_queue_management_thread"):
829
+ pool._start_queue_management_thread()
830
+ else:
831
+ for _ in range(n):
832
+ pool._adjust_process_count()
833
+ if hasattr(pool, "_start_executor_manager_thread"):
834
+ pool._start_executor_manager_thread()
835
+
836
+
837
+ class TestException(RuntimeError):
838
+ pass
839
+
840
+
841
+ def raise_testexc() -> Never:
842
+ raise TestException
843
+
844
+
845
+ def _test_signal_then_sleep(signal_path: str, seconds: float) -> None:
846
+ # Test helper: announce that this worker has begun executing by creating
847
+ # signal_path, then block. Lets a test wait until a job is actually running
848
+ # in a worker before acting on the pool (e.g. shutting it down).
849
+ Path(signal_path).touch()
850
+ time.sleep(seconds)
851
+
852
+
853
+ def _ignore_sigterm_and_sleep_for_test() -> None:
854
+ # Test helper: a compile worker that ignores SIGTERM and blocks, forcing pool
855
+ # teardown to escalate to SIGKILL instead of stalling on a graceful shutdown.
856
+ import signal
857
+
858
+ signal.signal(signal.SIGTERM, signal.SIG_IGN)
859
+ while True:
860
+ time.sleep(3600)
861
+
862
+
863
+ def _report_phase_and_sleep_for_test(phase: int, seconds: float) -> None:
864
+ # Test helper: report a heartbeat phase from a worker, then block, so the
865
+ # sidecar watchdog observes and reports that phase.
866
+ watchdog.report_phase(watchdog.Phase(phase))
867
+ time.sleep(seconds)
.venv/lib/python3.12/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
+
5
+
6
+ class Timer:
7
+ """
8
+ This measures how long we have gone since last receiving an event and if it is greater than a set interval, calls a function.
9
+ """
10
+
11
+ def __init__(
12
+ self,
13
+ duration: int | float, # Duration in seconds
14
+ call: Callable[[], None], # Function to call when we expire
15
+ ) -> None:
16
+ # We don't start the background thread until we actually get an event.
17
+ self.background_thread: Thread | None = None
18
+ self.last_called: float | None = None
19
+ self.duration = duration
20
+ self.sleep_time = duration / 2
21
+ self.call = call
22
+ self.exit = False
23
+
24
+ self.lock = Lock()
25
+
26
+ def record_call(self) -> None:
27
+ with self.lock:
28
+ if self.background_thread is None:
29
+ self.background_thread = Thread(
30
+ target=self.check, daemon=True, name="subproc_worker_timer"
31
+ )
32
+ self.background_thread.start()
33
+ self.last_called = monotonic()
34
+
35
+ def quit(self) -> None:
36
+ with self.lock:
37
+ self.exit = True
38
+
39
+ def check(self) -> None:
40
+ while True:
41
+ # We have to be sensitive on checking here, to avoid too much impact on cpu
42
+ sleep(self.sleep_time)
43
+ with self.lock:
44
+ if self.exit:
45
+ return
46
+ if self.last_called is None:
47
+ raise AssertionError("last_called must be set before timer check")
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.12/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, 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: int | None = None,
48
+ mp_context: BaseContext | None = None,
49
+ initializer: Callable[[], object] | None = 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.12/site-packages/torch/_inductor/compile_worker/utils.py ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import signal
3
+ from threading import Thread
4
+ from time import sleep
5
+
6
+ from torch._inductor.compile_worker import watchdog
7
+
8
+
9
+ _IN_TOPLEVEL_PROCESS = True
10
+
11
+
12
+ def in_toplevel_process() -> bool:
13
+ global _IN_TOPLEVEL_PROCESS
14
+ return _IN_TOPLEVEL_PROCESS
15
+
16
+
17
+ # If this process dies abnormally (e.g. segfault)
18
+ # it will not shut down the workers. Instead,
19
+ # the workers will have their parent reassigned to the
20
+ # init process. This launches a separate thread to
21
+ # watch for the worker getting reassigned,
22
+ # and cleans it up in this case.
23
+ #
24
+ # This function cannot be an inner function since otherwise mp_context="spawn" would
25
+ # not work for ProcessPoolExecutor since inner functions cannot be pickled.
26
+ def _async_compile_initializer(orig_ppid: int, close_fds: tuple[int, ...] = ()) -> None:
27
+ # In fork mode a worker inherits the sidecar's entire fd table, including the
28
+ # sidecar<->parent pipes. The worker must not keep those open: holding the
29
+ # result pipe's write end would stop the parent from ever seeing EOF when the
30
+ # sidecar dies. The caller only passes these fds under fork; under spawn the
31
+ # worker doesn't inherit them and the same integers would name unrelated fds
32
+ # the fresh interpreter reused, so closing them there would be silent
33
+ # corruption (the OSError guard wouldn't catch it) rather than a no-op.
34
+ for fd in close_fds:
35
+ try:
36
+ os.close(fd)
37
+ except OSError:
38
+ pass
39
+
40
+ import torch._C
41
+
42
+ def run() -> None:
43
+ while True:
44
+ sleep(60)
45
+ if orig_ppid != os.getppid():
46
+ os.kill(os.getpid(), signal.SIGKILL)
47
+
48
+ global _watchdog_thread, _original_parent
49
+ _original_parent = orig_ppid
50
+ _watchdog_thread = Thread(target=run, daemon=True)
51
+ _watchdog_thread.start()
52
+ # Ignore Ctrl-C (i.e. SIGINT) sent to pool workers to avoid meaningless log spam.
53
+ signal.signal(signal.SIGINT, signal.SIG_IGN)
54
+
55
+ # Install a crash handler to print out the stacktrace for SEGV
56
+ torch._C._initCrashHandler()
57
+
58
+ # Set a bit to distinguish async_compile subprocesses from the toplevel process.
59
+ global _IN_TOPLEVEL_PROCESS
60
+ _IN_TOPLEVEL_PROCESS = False
61
+
62
+ # Claim a heartbeat slot so the sidecar watchdog can report this worker's
63
+ # compile phase (no-op unless the sidecar allocated the shared buffer).
64
+ watchdog.init_worker_slot()
65
+
66
+
67
+ _watchdog_thread: Thread | None = None
68
+ _original_parent: int | None = None
69
+
70
+
71
+ def has_parent_changed() -> bool:
72
+ return _original_parent != os.getppid()
.venv/lib/python3.12/site-packages/torch/_inductor/compile_worker/watchdog.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared-memory heartbeat so the compile-worker sidecar's watchdog can report
2
+ which phase a slow/stuck worker is in (see SubprocMain._watchdog_loop).
3
+
4
+ A single multiprocessing.Array is allocated in the sidecar (create()) before it
5
+ forks its worker pool; every forked worker inherits the same buffer and writes
6
+ only its own slot -- single writer per slot, so no lock is needed there and a
7
+ rare torn read is harmless for a coarse once-a-minute diagnostic. The sidecar's
8
+ watchdog thread reads all slots.
9
+
10
+ Slots are recycled off the pool's lifecycle rather than by polling worker
11
+ liveness: the sidecar calls reset() every time it (re)builds the worker pool,
12
+ and workers then claim slots 0..nprocs-1 with a per-generation counter. A worker
13
+ death tears down and rebuilds the whole pool (ProcessPoolExecutor's behavior), so
14
+ reset() runs before the replacement generation forks and there is never more than
15
+ one live worker per slot. (If the pool were ever configured to replace workers
16
+ individually -- e.g. max_tasks_per_child -- a replacement would simply run out of
17
+ counter and report nothing, rather than collide with a live worker's slot.)
18
+
19
+ Everything is a no-op unless the sidecar allocated the buffer and the worker
20
+ claimed a slot, so the report_phase() calls sprinkled through the compile path
21
+ are free in the main process and in non-forking pools (spawn workers do not
22
+ inherit the buffer and simply degrade to duration-only reporting).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import multiprocessing
28
+ import os
29
+ import time
30
+ from enum import IntEnum
31
+ from typing import Any
32
+
33
+
34
+ class Phase(IntEnum):
35
+ # Persisted as ints in the shared buffer; append new phases, don't renumber.
36
+ RUNNING = 0
37
+ QUERYING_CACHE = 1
38
+ COMPILING = 2
39
+
40
+
41
+ # Per-slot layout: _FIELDS longs.
42
+ _FIELDS = 4
43
+ _F_JOB_ID = 0
44
+ _F_PHASE = 1
45
+ _F_PHASE_START_NS = 2
46
+ _F_PID = 3
47
+ _EMPTY = -1 # job_id sentinel for an idle slot
48
+
49
+ # Allocated in the sidecar (create) before forking; inherited by fork workers.
50
+ # _counter's lock also serializes slot claims and reset().
51
+ _heartbeat: Any | None = None
52
+ _counter: Any | None = None
53
+ _nprocs: int = 0
54
+ # Claimed post-fork by each worker (init_worker_slot).
55
+ _slot: int | None = None
56
+
57
+
58
+ def create(nprocs: int) -> None:
59
+ """Sidecar: allocate the shared buffer before forking the worker pool."""
60
+ global _heartbeat, _counter, _nprocs
61
+ ctx = multiprocessing.get_context("fork")
62
+ _nprocs = nprocs
63
+ _counter = ctx.Value("i", 0)
64
+ buf = ctx.Array("q", nprocs * _FIELDS, lock=False)
65
+ for s in range(nprocs):
66
+ buf[s * _FIELDS + _F_JOB_ID] = _EMPTY
67
+ _heartbeat = buf
68
+
69
+
70
+ def reset() -> None:
71
+ """Sidecar: recycle all slots for a fresh worker generation. Call before
72
+ (re)building the worker pool so the new workers claim clean slots 0..n-1."""
73
+ if _heartbeat is None or _counter is None:
74
+ return
75
+ with _counter.get_lock():
76
+ _counter.value = 0
77
+ for s in range(_nprocs):
78
+ base = s * _FIELDS
79
+ _heartbeat[base + _F_JOB_ID] = _EMPTY
80
+ _heartbeat[base + _F_PID] = 0
81
+
82
+
83
+ def init_worker_slot() -> None:
84
+ """Worker: claim this generation's next slot. No-op if the sidecar didn't
85
+ allocate a buffer (main process / spawn pools)."""
86
+ global _slot
87
+ if _heartbeat is None or _counter is None or _nprocs <= 0:
88
+ return
89
+ with _counter.get_lock():
90
+ slot = _counter.value
91
+ _counter.value = slot + 1
92
+ # Only the first nprocs workers of a generation get a slot; any beyond that
93
+ # (which shouldn't happen without per-worker replacement) report nothing.
94
+ if slot < _nprocs:
95
+ _slot = slot
96
+ _heartbeat[slot * _FIELDS + _F_PID] = os.getpid()
97
+
98
+
99
+ def set_current_job(job_id: int) -> None:
100
+ """Worker: mark the start of a job in this worker's slot."""
101
+ if _heartbeat is None or _slot is None:
102
+ return
103
+ base = _slot * _FIELDS
104
+ _heartbeat[base + _F_PHASE] = int(Phase.RUNNING)
105
+ _heartbeat[base + _F_PHASE_START_NS] = time.monotonic_ns()
106
+ # Written last so a concurrent reader sees a fully-populated slot or none.
107
+ _heartbeat[base + _F_JOB_ID] = job_id
108
+
109
+
110
+ def report_phase(phase: Phase) -> None:
111
+ """Worker: record the phase this worker just entered."""
112
+ if _heartbeat is None or _slot is None:
113
+ return
114
+ base = _slot * _FIELDS
115
+ _heartbeat[base + _F_PHASE_START_NS] = time.monotonic_ns()
116
+ _heartbeat[base + _F_PHASE] = int(phase)
117
+
118
+
119
+ def clear_current_job() -> None:
120
+ """Worker: mark this slot idle when its job finishes."""
121
+ if _heartbeat is None or _slot is None:
122
+ return
123
+ _heartbeat[_slot * _FIELDS + _F_JOB_ID] = _EMPTY
124
+
125
+
126
+ def enabled() -> bool:
127
+ """Sidecar: whether phase heartbeats are active (fork pools only)."""
128
+ return _heartbeat is not None
129
+
130
+
131
+ def read_heartbeats() -> dict[int, tuple[int, int, int]]:
132
+ """Sidecar: job_id -> (phase, phase_start_ns, pid) for currently-busy slots.
133
+
134
+ phase_start_ns is worker monotonic_ns; on Linux CLOCK_MONOTONIC is
135
+ system-wide so the sidecar can diff it against its own monotonic_ns.
136
+ """
137
+ if _heartbeat is None:
138
+ return {}
139
+ out: dict[int, tuple[int, int, int]] = {}
140
+ for s in range(_nprocs):
141
+ base = s * _FIELDS
142
+ job_id = _heartbeat[base + _F_JOB_ID]
143
+ if job_id != _EMPTY:
144
+ out[job_id] = (
145
+ _heartbeat[base + _F_PHASE],
146
+ _heartbeat[base + _F_PHASE_START_NS],
147
+ _heartbeat[base + _F_PID],
148
+ )
149
+ return out
.venv/lib/python3.12/site-packages/torch/_inductor/compiler_bisector.py ADDED
@@ -0,0 +1,833 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import atexit
2
+ import collections
3
+ import dataclasses
4
+ import functools
5
+ import os
6
+ import shutil
7
+ import sys
8
+ import tempfile
9
+ from collections.abc import Callable
10
+ from dataclasses import dataclass, field
11
+
12
+ from torch._inductor.runtime.cache_dir_utils import cache_dir
13
+
14
+
15
+ # Set the subdirectory name
16
+ SUBDIR_NAME = "bisect"
17
+
18
+
19
+ @dataclass
20
+ class Subsystem:
21
+ name: str
22
+
23
+
24
+ @dataclass
25
+ class BisectSubsystem(Subsystem):
26
+ pass
27
+
28
+
29
+ @dataclass
30
+ class BinarySubsystem(Subsystem):
31
+ pass
32
+
33
+
34
+ @dataclass
35
+ class ConfigChange(BinarySubsystem):
36
+ name: str = field(init=False)
37
+ config_name: str
38
+ config_field: str
39
+ config_value: object
40
+
41
+ def __post_init__(self) -> None:
42
+ self.name = f"{self.config_name}_{self.config_field}"
43
+
44
+
45
+ # Dictionary of backend -> subsystems
46
+ BACKENDS: dict[str, list[Subsystem]] = {
47
+ # run dynamo without aot_autograd
48
+ "eager": [],
49
+ # run dynamo with aot_autograd, but no partitioner or decomps
50
+ "aot_eager": [],
51
+ # run dynamo with aot autograd, decompositions and partitioner
52
+ "aot_eager_decomp_partition": [
53
+ ConfigChange("aot_eager_decomp_partition", "cse", False),
54
+ BisectSubsystem(
55
+ "decomposition"
56
+ ), # number of decompositions we apply in tracing
57
+ ], # TODO - add cse ?
58
+ # applies CrossRefFakeMode on invocation
59
+ "aot_eager_decomp_partition_crossref": [],
60
+ "inductor": [
61
+ BisectSubsystem("pre_grad_passes"), # passes applied on pre-grad IR
62
+ BisectSubsystem("joint_graph_passes"), # passes applied on joint graph
63
+ BisectSubsystem(
64
+ "post_grad_passes"
65
+ ), # passes applied individually on forward, and backward in inductor
66
+ ConfigChange("inductor", "fallback_random", True),
67
+ ConfigChange("inductor", "emulate_precision_casts", True),
68
+ ConfigChange("inductor", "layout_optimization", False),
69
+ ConfigChange("inductor", "comprehensive_padding", False),
70
+ BisectSubsystem("cudagraphs"), # cudagraph wrapping of compiled graphs
71
+ BisectSubsystem("lowerings"), # lowering aten operators to inductor
72
+ ], # TODO - add more - fusions ?
73
+ }
74
+
75
+ subsystem_call_counter: dict[str, int] = collections.Counter()
76
+
77
+
78
+ @functools.cache
79
+ def get_env_val(env_str: str) -> str | None:
80
+ return os.environ.get(env_str, None)
81
+
82
+
83
+ @dataclasses.dataclass
84
+ class BisectionResult:
85
+ """
86
+ backend: torch.compile backend responsible for failure
87
+ subsystem: optional, registered component identified for failure
88
+ bisect_number: optional, number of times the subsystem needed to be applied to trigger failure
89
+ debug_info: associated info of the triggering bisect application of subsystem
90
+ """
91
+
92
+ backend: str
93
+ subsystem: str | None = None
94
+ bisect_number: int | None = None
95
+ debug_info: str | None = None
96
+
97
+
98
+ class CompilerBisector:
99
+ """
100
+ This class iteratively runs torch.compile backends (eager, aot_eager, inductor) to find the
101
+ first backend that can repro an issue.
102
+
103
+ Once it discovers the offending backend it will iteratively disable subsystems within the backend.
104
+ For subsystems which are applied repeatedly, such as the number of post grad passes or number
105
+ of lowering of nodes to inductor ir, it will bisect to find the offending application.
106
+
107
+ The idiomatic way to run it is with `do_bisect`. You can also use it by setting the env flags
108
+ `TORCH_BISECT_BACKEND`, `TORCH_BISECT_SUBSYSTEM` and `TORCH_BISECT_MAX`.
109
+
110
+ It also supports a CLI interface:
111
+
112
+ python -m torch._inductor.compiler_bisector start
113
+ python -m torch._inductor.compiler_bisector good
114
+ python -m torch._inductor.compiler_bisector bad
115
+ python -m torch._inductor.compiler_bisector end
116
+
117
+ Or use `run` to automatically bisect by running a command repeatedly:
118
+
119
+ python -m torch._inductor.compiler_bisector run <command>
120
+
121
+ The command's exit code determines the result: 0 = good, non-zero = bad.
122
+ The TORCH_COMPILE_BACKEND env var is set to the backend being tested.
123
+ """
124
+
125
+ bisection_enabled: bool = False
126
+
127
+ in_process_cache: str | None = None
128
+
129
+ @classmethod
130
+ def clear_call_counter_debug_info(
131
+ cls, backend_name: str, subsystem_name: str
132
+ ) -> None:
133
+ file_path = os.path.join(
134
+ cls.get_dir(),
135
+ backend_name,
136
+ f"{subsystem_name}_call_counter_debug_info.txt",
137
+ )
138
+ cls.write_lines_to_file(file_path, [])
139
+
140
+ @classmethod
141
+ def reset_counters(cls) -> None:
142
+ subsystem_call_counter.clear()
143
+ for backend, subsystem_list in BACKENDS.items():
144
+ for subsystem in subsystem_list:
145
+ if isinstance(subsystem, BisectSubsystem):
146
+ cls.clear_call_counter_debug_info(backend, subsystem.name)
147
+
148
+ @classmethod
149
+ def get_dir(cls) -> str:
150
+ return f"{cache_dir() if not cls.in_process_cache else cls.in_process_cache}/{SUBDIR_NAME}"
151
+
152
+ @classmethod
153
+ def write_lines_to_file(
154
+ cls, file_path: str, lines: list[str], *, append: bool = False
155
+ ) -> None:
156
+ os.makedirs(os.path.dirname(file_path), exist_ok=True)
157
+ with open(file_path, "a" if append else "w") as file:
158
+ file.writelines(lines)
159
+
160
+ @classmethod
161
+ def read_lines_from_file(cls, file_path: str) -> list[str]:
162
+ if os.path.exists(file_path):
163
+ with open(file_path) as file:
164
+ return file.readlines()
165
+ return []
166
+
167
+ @classmethod
168
+ def update_run_state(
169
+ cls, backend_name: str, subsystem: Subsystem, run_state: str
170
+ ) -> None:
171
+ file_path = os.path.join(
172
+ cls.get_dir(), backend_name, f"{subsystem.name}_run_state.txt"
173
+ )
174
+ if isinstance(subsystem, ConfigChange):
175
+ if run_state != "test_disable":
176
+ raise AssertionError(
177
+ f"expected run_state == 'test_disable', got {run_state}"
178
+ )
179
+ cls.set_config_values(
180
+ backend_name,
181
+ subsystem.name,
182
+ {subsystem.config_field: subsystem.config_value},
183
+ )
184
+
185
+ cls.write_lines_to_file(file_path, [run_state])
186
+
187
+ @classmethod
188
+ def set_config_values(
189
+ cls, backend: str, subsystem: str, config_data: dict[str, object]
190
+ ) -> None:
191
+ file_path = os.path.join(cls.get_dir(), backend, f"{subsystem}_config.txt")
192
+ lines = [f"{k}={v}\n" for k, v in config_data.items()]
193
+ cls.write_lines_to_file(file_path, lines)
194
+
195
+ @classmethod
196
+ def update_bisect_status(cls, backend_name: str, subsystem_name: str) -> None:
197
+ if not isinstance(subsystem_name, str):
198
+ raise AssertionError(
199
+ f"expected subsystem_name to be str, got {type(subsystem_name)}"
200
+ )
201
+ file_path = os.path.join(cls.get_dir(), "bisect_status.txt")
202
+ lines = [f"backend={backend_name}\n", f"subsystem={subsystem_name}\n"]
203
+ cls.write_lines_to_file(file_path, lines)
204
+
205
+ @classmethod
206
+ def update_bisect_range(
207
+ cls, backend_name: str, subsystem_name: str, low: int, high: int
208
+ ) -> None:
209
+ if not isinstance(subsystem_name, str):
210
+ raise AssertionError(
211
+ f"expected subsystem_name to be str, got {type(subsystem_name)}"
212
+ )
213
+ file_path = os.path.join(
214
+ cls.get_dir(), backend_name, f"{subsystem_name}_bisect_range.txt"
215
+ )
216
+ lines = [f"low={low}\n", f"high={high}\n"]
217
+ cls.write_lines_to_file(file_path, lines)
218
+
219
+ @classmethod
220
+ def add_call_counter_debug_info(
221
+ cls, backend_name: str, subsystem_name: str, call_counter: int, debug_info: str
222
+ ) -> None:
223
+ file_path = os.path.join(
224
+ cls.get_dir(), backend_name, f"{subsystem_name}_call_counter_debug_info.txt"
225
+ )
226
+ # This is only called for the last ~2 items in a bisect, so writing duplicate
227
+ # lines does not have performance implications later.
228
+ lines = [f"{call_counter}={debug_info}\n"]
229
+ cls.write_lines_to_file(file_path, lines, append=True)
230
+
231
+ @classmethod
232
+ def get_call_counter_debug_info(
233
+ cls, backend_name: str, subsystem_name: str, call_counter: int
234
+ ) -> str | None:
235
+ file_path = os.path.join(
236
+ cls.get_dir(), backend_name, f"{subsystem_name}_call_counter_debug_info.txt"
237
+ )
238
+ call_counter_str = str(call_counter)
239
+ for line in reversed(cls.read_lines_from_file(file_path)):
240
+ counter, _, debug_info = line.strip().partition("=")
241
+ if counter == call_counter_str:
242
+ return debug_info
243
+ return None
244
+
245
+ @classmethod
246
+ def get_backend(cls) -> str | None:
247
+ """
248
+ Returns the active backend, if any
249
+ """
250
+ if val := get_env_val("TORCH_BISECT_BACKEND"):
251
+ return val
252
+
253
+ file_path = os.path.join(cls.get_dir(), "bisect_status.txt")
254
+ lines = cls.read_lines_from_file(file_path)
255
+ for line in lines:
256
+ if line.startswith("backend="):
257
+ return line.strip().split("=")[1]
258
+ return None
259
+
260
+ @classmethod
261
+ def get_subsystem(cls) -> str | None:
262
+ """
263
+ Returns the active subsystem, if any
264
+ """
265
+
266
+ if val := get_env_val("TORCH_BISECT_SUBSYSTEM"):
267
+ return val
268
+
269
+ file_path = os.path.join(cls.get_dir(), "bisect_status.txt")
270
+ lines = cls.read_lines_from_file(file_path)
271
+ for line in lines:
272
+ if line.startswith("subsystem="):
273
+ out = line.strip().split("=")[1]
274
+ return out or None
275
+ return None
276
+
277
+ @classmethod
278
+ def get_subsystem_object(cls, backend_name: str, subsystem_name: str) -> Subsystem:
279
+ return next(obj for obj in BACKENDS[backend_name] if obj.name == subsystem_name)
280
+
281
+ @classmethod
282
+ def get_run_state(cls, backend_name: str, subsystem_name: str) -> str | None:
283
+ """
284
+ Returns the current stage of bisecting, if Any
285
+ """
286
+
287
+ file_path = os.path.join(
288
+ cls.get_dir(), backend_name, f"{subsystem_name}_run_state.txt"
289
+ )
290
+ lines = cls.read_lines_from_file(file_path)
291
+ if lines:
292
+ out = lines[0].strip()
293
+ if out not in ("test_disable", "find_max_bounds", "bisect"):
294
+ raise AssertionError(
295
+ f"unexpected run_state {out!r}, expected one of "
296
+ "'test_disable', 'find_max_bounds', 'bisect'"
297
+ )
298
+ return out
299
+ return None
300
+
301
+ @classmethod
302
+ def get_bisect_range(
303
+ cls, backend_name: str, subsystem_name: str
304
+ ) -> tuple[int, int]:
305
+ file_path = os.path.join(
306
+ cls.get_dir(), backend_name, f"{subsystem_name}_bisect_range.txt"
307
+ )
308
+ lines = cls.read_lines_from_file(file_path)
309
+ low = None
310
+ high = None
311
+ # pyrefly: ignore [bad-assignment]
312
+ for line in reversed(lines):
313
+ if line.startswith("low="):
314
+ low = int(line.strip().split("=")[1])
315
+ elif line.startswith("high="):
316
+ high = int(line.strip().split("=")[1])
317
+
318
+ if low is not None and high is not None:
319
+ break
320
+
321
+ if low is None or high is None:
322
+ raise RuntimeError(
323
+ f"Trying to get bisect range when it is not set: subsystem {subsystem_name}"
324
+ )
325
+
326
+ return low, high
327
+
328
+ @classmethod
329
+ def update_config_change(cls, backend: str, subsystem: ConfigChange) -> None:
330
+ file_path = os.path.join(cls.get_dir(), backend, f"{subsystem.name}_config.txt")
331
+ lines = [
332
+ f"config_name={subsystem.config_name}\n",
333
+ f"config_field={subsystem.config_field}\n",
334
+ f"config_value={subsystem.config_value}\n",
335
+ ]
336
+ cls.write_lines_to_file(file_path, lines)
337
+
338
+ @classmethod
339
+ def get_config_change(cls, config_name: str) -> dict[str, object] | None:
340
+ backend = cls.get_backend()
341
+ subsystem = cls.get_subsystem()
342
+
343
+ if not backend or not subsystem:
344
+ return None
345
+
346
+ file_path = os.path.join(cls.get_dir(), backend, f"{subsystem}_config.txt")
347
+
348
+ if not os.path.exists(file_path):
349
+ return None
350
+
351
+ lines = cls.read_lines_from_file(file_path)
352
+ config_data = {}
353
+ for line in lines:
354
+ key, value = line.strip().split("=", 1)
355
+ config_data[key] = eval(value)
356
+
357
+ return config_data
358
+
359
+ @classmethod
360
+ def delete_bisect_status(cls) -> None:
361
+ # in process_cache we have created if it exists, just the subdirectory of non created dir
362
+ dir_name = cls.in_process_cache or cls.get_dir()
363
+ if os.path.exists(dir_name):
364
+ shutil.rmtree(dir_name)
365
+ print("Bisection status deleted.")
366
+ else:
367
+ print("No bisection status found.")
368
+
369
+ @classmethod
370
+ def get_system_counter(cls, name: str, increment: bool = True) -> int:
371
+ global subsystem_call_counter
372
+ curr = subsystem_call_counter[name]
373
+ if increment:
374
+ subsystem_call_counter[name] += 1
375
+ return curr
376
+
377
+ @classmethod
378
+ def disable_subsystem(
379
+ cls,
380
+ backend: str,
381
+ subsystem: str,
382
+ debug_info: Callable[[], str] | None = None,
383
+ ) -> bool:
384
+ if not cls.bisection_enabled:
385
+ return False
386
+
387
+ if cls.get_backend() != backend:
388
+ return False
389
+
390
+ if cls.get_subsystem() != subsystem:
391
+ return False
392
+
393
+ if val := get_env_val("TORCH_BISECT_MAX"):
394
+ counter = cls.get_system_counter(subsystem, increment=True)
395
+ return counter > int(val)
396
+
397
+ run_state = cls.get_run_state(backend, subsystem)
398
+ if run_state == "test_disable":
399
+ # First run, disable completely
400
+ return True
401
+ elif run_state == "find_max_bounds":
402
+ # Second run, update bisection range and return True to enable the subsystem
403
+ cls.update_bisect_range(
404
+ backend,
405
+ subsystem,
406
+ 0,
407
+ cls.get_system_counter(subsystem, increment=True),
408
+ )
409
+ return False
410
+ else:
411
+ if run_state != "bisect":
412
+ raise AssertionError(f"expected run_state == 'bisect', got {run_state}")
413
+ # If the environment variable is not set, use the bisection range midpoint
414
+ low, high = cls.get_bisect_range(backend, subsystem)
415
+ # if high - low <= 2:
416
+ midpoint = (low + high) // 2
417
+ call_counter = cls.get_system_counter(subsystem)
418
+
419
+ if (
420
+ call_counter >= low
421
+ and call_counter <= high
422
+ and (high - low) <= 2
423
+ and debug_info is not None
424
+ ):
425
+ cls.add_call_counter_debug_info(
426
+ backend, subsystem, call_counter, debug_info()
427
+ )
428
+
429
+ return call_counter > midpoint
430
+
431
+ @classmethod
432
+ def advance_subsystem(
433
+ cls, curr_backend: str, curr_subsystem: Subsystem
434
+ ) -> Subsystem | None:
435
+ """
436
+ Tries to move to the next subsystem within the current system.
437
+ """
438
+ print(f"Disabling {curr_subsystem.name} did not fix the issue.")
439
+
440
+ current_subsystems = BACKENDS[curr_backend]
441
+ current_subsystem_index = next(
442
+ i
443
+ for i, subsystem in enumerate(current_subsystems)
444
+ if subsystem.name == curr_subsystem.name
445
+ )
446
+
447
+ if current_subsystem_index < len(current_subsystems) - 1:
448
+ next_subsystem = current_subsystems[current_subsystem_index + 1]
449
+ cls.update_bisect_status(curr_backend, next_subsystem.name)
450
+ cls.update_run_state(curr_backend, next_subsystem, "test_disable")
451
+ print(
452
+ f"Moving to the next subsystem: {curr_backend} - {next_subsystem.name}"
453
+ )
454
+ return next_subsystem
455
+ else:
456
+ print(
457
+ f"All subsystems in {curr_backend} have been checked. The issue is not in this system."
458
+ )
459
+ return None
460
+
461
+ @classmethod
462
+ def advance_backend(cls, curr_backend: str) -> str | None:
463
+ """
464
+ Tries Move to the next backend.
465
+ """
466
+ current_system_index = list(BACKENDS.keys()).index(curr_backend)
467
+
468
+ if current_system_index < len(BACKENDS) - 1:
469
+ curr_backend = list(BACKENDS.keys())[current_system_index + 1]
470
+ cls.update_bisect_status(curr_backend, "")
471
+ print(f"Moving to the next system: {curr_backend}")
472
+ return curr_backend
473
+ else:
474
+ return None
475
+
476
+ @classmethod
477
+ def process_subsystem(
478
+ cls,
479
+ curr_backend: str,
480
+ curr_subsystem: Subsystem,
481
+ fn: Callable[[], bool],
482
+ cli_interface: bool = True,
483
+ ) -> bool:
484
+ """
485
+ Process the current subsystem. Returns True if the issue is found, False otherwise.
486
+ """
487
+ if not isinstance(curr_subsystem, Subsystem):
488
+ raise AssertionError(
489
+ f"expected curr_subsystem to be Subsystem, got {type(curr_subsystem)}"
490
+ )
491
+ while True:
492
+ run_state = cls.get_run_state(curr_backend, curr_subsystem.name)
493
+ cls.reset_counters()
494
+ if run_state == "test_disable":
495
+ if not fn():
496
+ next_subsystem = cls.advance_subsystem(curr_backend, curr_subsystem)
497
+ if not next_subsystem:
498
+ return False
499
+ curr_subsystem = next_subsystem
500
+ else:
501
+ if isinstance(curr_subsystem, ConfigChange):
502
+ print(
503
+ f"Setting config {curr_subsystem.config_name} field {curr_subsystem.config_field} "
504
+ f"to {curr_subsystem.config_value} fixed the issue"
505
+ )
506
+ else:
507
+ print(f"Disabling {curr_subsystem.name} fixed the issue.")
508
+ if isinstance(curr_subsystem, BinarySubsystem):
509
+ return True
510
+ print("Starting bisect by getting upper bound.")
511
+ cls.update_run_state(
512
+ curr_backend, curr_subsystem, "find_max_bounds"
513
+ )
514
+ elif run_state == "find_max_bounds":
515
+ if fn():
516
+ raise RuntimeError(
517
+ f"Function succeeded with 'find_max_bounds' status for {curr_backend} - {curr_subsystem.name}."
518
+ )
519
+ else:
520
+ _, high = cls.get_bisect_range(curr_backend, curr_subsystem.name)
521
+ print(f"Upper bound of {high} found for {curr_backend}.")
522
+ cls.update_run_state(curr_backend, curr_subsystem, "bisect")
523
+ elif run_state == "bisect":
524
+ low, high = cls.get_bisect_range(curr_backend, curr_subsystem.name)
525
+ midpoint = (low + high) // 2
526
+ print(
527
+ f"Bisecting {curr_backend} - {curr_subsystem.name} (Range: [{low}, {high}], Midpoint: {midpoint})"
528
+ )
529
+ if fn():
530
+ cls.update_bisect_range(
531
+ curr_backend, curr_subsystem.name, midpoint + 1, high
532
+ )
533
+ else:
534
+ cls.update_bisect_range(
535
+ curr_backend, curr_subsystem.name, low, midpoint
536
+ )
537
+ low, high = cls.get_bisect_range(curr_backend, curr_subsystem.name)
538
+ if low == high:
539
+ print(
540
+ f"Binary search completed for {curr_backend} - {curr_subsystem.name}. The bisect number is {low}. "
541
+ f"Debug info: {cls.get_call_counter_debug_info(curr_backend, curr_subsystem.name, low) or 'not found'}"
542
+ )
543
+ return True
544
+ else:
545
+ raise RuntimeError(f"Unexpected run_state {run_state}")
546
+
547
+ if cli_interface:
548
+ sys.exit(0)
549
+
550
+ @classmethod
551
+ def initialize_system(cls) -> None:
552
+ curr_backend = next(iter(BACKENDS.keys()))
553
+ curr_subsystem = ""
554
+ cls.update_bisect_status(curr_backend, curr_subsystem)
555
+ print(f"Starting bisection process with system: {curr_backend}")
556
+
557
+ @classmethod
558
+ def do_bisect(
559
+ cls, fn: Callable[[], bool], cli_interface: bool = False
560
+ ) -> BisectionResult | None:
561
+ """
562
+ Run fn repeatedly attempting to bisect torch.compile. fn should return True on success and False on failure.
563
+ """
564
+
565
+ # TODO graph bisecting is not well composed with lowering
566
+ # bisector so far. Use a config to opt-in
567
+ import torch._inductor.config as inductor_config
568
+
569
+ if inductor_config.test_configs.bisect_pre_grad_graph:
570
+ BACKENDS["inductor"].insert(0, BisectSubsystem("pre_grad_graph"))
571
+
572
+ if not cli_interface:
573
+ bisection_enabled_orig = cls.bisection_enabled
574
+ cls.delete_bisect_status()
575
+ cls.bisection_enabled = True
576
+ # Only create temp dir if not already set (CLI run mode pre-sets it)
577
+ if not cls.in_process_cache:
578
+ cls.in_process_cache = tempfile.mkdtemp()
579
+
580
+ def cleanup() -> None:
581
+ cls.bisection_enabled = bisection_enabled_orig
582
+ cls.delete_bisect_status()
583
+ cls.in_process_cache = None
584
+
585
+ if BACKENDS["inductor"][0].name == "pre_grad_graph":
586
+ del BACKENDS["inductor"][0]
587
+
588
+ cleanup_handler = atexit.register(cleanup)
589
+
590
+ class DisableBisect:
591
+ def __del__(self) -> None:
592
+ cleanup()
593
+ atexit.unregister(cleanup_handler)
594
+
595
+ _cleanup = DisableBisect()
596
+
597
+ curr_backend = cls.get_backend()
598
+ curr_subsystem_name = cls.get_subsystem()
599
+
600
+ if not curr_backend:
601
+ cls.initialize_system()
602
+ curr_backend = cls.get_backend()
603
+ if curr_backend is None:
604
+ raise AssertionError(
605
+ "expected curr_backend to be set after initialize_system"
606
+ )
607
+ curr_subsystem_name = cls.get_subsystem()
608
+
609
+ curr_subsystem = (
610
+ cls.get_subsystem_object(curr_backend, curr_subsystem_name)
611
+ if curr_subsystem_name is not None
612
+ else None
613
+ )
614
+ while True:
615
+ if curr_backend is None:
616
+ raise AssertionError("expected curr_backend to be set")
617
+ cls.reset_counters()
618
+ if curr_subsystem:
619
+ result = cls.process_subsystem(
620
+ curr_backend, curr_subsystem, fn, cli_interface=cli_interface
621
+ )
622
+ if result:
623
+ curr_subsystem = cls.get_subsystem_object(
624
+ curr_backend,
625
+ cls.get_subsystem(), # type: ignore[arg-type]
626
+ )
627
+
628
+ if isinstance(curr_subsystem, BinarySubsystem):
629
+ return BisectionResult(
630
+ curr_backend,
631
+ curr_subsystem.name,
632
+ 0,
633
+ curr_subsystem.name,
634
+ )
635
+
636
+ low, _ = cls.get_bisect_range(curr_backend, curr_subsystem.name)
637
+ return BisectionResult(
638
+ curr_backend,
639
+ curr_subsystem.name,
640
+ low,
641
+ cls.get_call_counter_debug_info(
642
+ curr_backend, curr_subsystem.name, low
643
+ ),
644
+ )
645
+
646
+ next_subsystem = cls.advance_subsystem(curr_backend, curr_subsystem)
647
+ if not next_subsystem:
648
+ print(
649
+ f"The issue is in the {curr_backend} system, but could not identify subsystem."
650
+ )
651
+ if curr_backend is None:
652
+ raise AssertionError("expected curr_backend to be set")
653
+ return BisectionResult(curr_backend)
654
+
655
+ curr_subsystem = next_subsystem
656
+ else:
657
+ if fn():
658
+ next_backend = cls.advance_backend(curr_backend)
659
+ if not next_backend:
660
+ print("All systems have been checked.")
661
+ return None
662
+
663
+ curr_backend = next_backend
664
+ else:
665
+ current_subsystems = BACKENDS[curr_backend]
666
+ if current_subsystems:
667
+ curr_subsystem = current_subsystems[0]
668
+ cls.update_bisect_status(curr_backend, curr_subsystem.name)
669
+ cls.update_run_state(
670
+ curr_backend, curr_subsystem, "test_disable"
671
+ )
672
+ print(
673
+ f"The issue is in the {curr_backend} system. Moving to the first subsystem: {curr_subsystem}"
674
+ )
675
+ else:
676
+ print(f"The issue is in the {curr_backend} system.")
677
+ return BisectionResult(curr_backend)
678
+
679
+ if cli_interface:
680
+ sys.exit(0)
681
+
682
+
683
+ HELP_TEXT = """\
684
+ Usage: python -m torch._inductor.compiler_bisector <command>
685
+
686
+ Commands:
687
+ start Start a new bisection session (manual mode)
688
+ good Mark the current state as good (no issue)
689
+ bad Mark the current state as bad (issue present)
690
+ end End the bisection session and clean up
691
+ run <cmd> Automatically bisect by running a command repeatedly
692
+ Exit code 0 = good, non-zero = bad
693
+
694
+ Example - using 'run' for automatic bisection:
695
+
696
+ 1. Create a test script (e.g., test_bug.py):
697
+
698
+ import os, sys, torch
699
+
700
+ def main():
701
+ torch._dynamo.reset()
702
+ # Use the backend the bisector is testing
703
+ backend = os.environ.get("TORCH_COMPILE_BACKEND", "inductor")
704
+
705
+ @torch.compile(backend=backend)
706
+ def fn(x):
707
+ return x.sin() # or your failing operation
708
+
709
+ x = torch.randn(10)
710
+ compiled = fn(x)
711
+ expected = x.sin() # eager reference
712
+
713
+ if torch.allclose(compiled, expected, rtol=1e-4, atol=1e-4):
714
+ return 0 # PASS
715
+ else:
716
+ print(f"FAIL: got {compiled}, expected {expected}")
717
+ return 1 # FAIL
718
+
719
+ if __name__ == "__main__":
720
+ sys.exit(main())
721
+
722
+ 2. Run the bisector:
723
+
724
+ python -m torch._inductor.compiler_bisector run python test_bug.py
725
+
726
+ 3. The bisector will:
727
+ - Test backends (eager, aot_eager, inductor) to find which fails
728
+ - Test subsystems within that backend (passes, lowerings, etc.)
729
+ - Binary search to find the exact operation causing the issue
730
+
731
+ Output:
732
+ Disabling lowerings fixed the issue.
733
+ Binary search completed for inductor - lowerings. The bisect number is 42.
734
+ Bisection complete: BisectionResult(backend='inductor', subsystem='lowerings', ...)
735
+
736
+ Environment variables set for your test script:
737
+ TORCH_COMPILE_BACKEND - The backend being tested (use this in torch.compile)
738
+ """
739
+
740
+
741
+ def command_line_usage() -> None:
742
+ """Entry point for the compiler bisector command-line interface."""
743
+ if len(sys.argv) < 2:
744
+ print(HELP_TEXT)
745
+ sys.exit(1)
746
+
747
+ bisection_manager = CompilerBisector()
748
+ command = sys.argv[1]
749
+
750
+ if command == "end":
751
+ bisection_manager.delete_bisect_status()
752
+ sys.exit(0)
753
+
754
+ if command == "start":
755
+ bisection_manager.delete_bisect_status()
756
+ bisection_manager.initialize_system()
757
+ sys.exit(0)
758
+
759
+ if command == "run":
760
+ if len(sys.argv) < 3:
761
+ print(
762
+ "Usage: python -m torch._inductor.compiler_bisector run <command> [args...]"
763
+ )
764
+ sys.exit(1)
765
+
766
+ import subprocess
767
+
768
+ run_cmd = sys.argv[2:]
769
+
770
+ def test_function() -> bool:
771
+ # Pass bisection state to subprocess via environment variables
772
+ env = os.environ.copy()
773
+ backend = bisection_manager.get_backend()
774
+ subsystem = bisection_manager.get_subsystem()
775
+
776
+ if backend:
777
+ # For test script to select the right backend
778
+ env["TORCH_COMPILE_BACKEND"] = backend
779
+ # For bisector in subprocess to know which backend we're testing
780
+ env["TORCH_BISECT_BACKEND"] = backend
781
+
782
+ if subsystem:
783
+ if backend is None: # subsystem requires a backend
784
+ raise AssertionError("subsystem requires a backend")
785
+ env["TORCH_BISECT_SUBSYSTEM"] = subsystem
786
+ # Get run_state to determine TORCH_BISECT_MAX
787
+ run_state = bisection_manager.get_run_state(backend, subsystem)
788
+ if run_state == "test_disable":
789
+ # -1 means always disable (counter > -1 is always True)
790
+ env["TORCH_BISECT_MAX"] = "-1"
791
+ # For find_max_bounds and bisect, let the subprocess use file-based
792
+ # mechanisms. The subprocess reads run_state and bisect_range from
793
+ # files, and writes the actual count during find_max_bounds.
794
+
795
+ result = subprocess.run(run_cmd, env=env)
796
+ return result.returncode == 0
797
+
798
+ bisection_manager.delete_bisect_status()
799
+ bisection_manager.bisection_enabled = True
800
+ # Use shared cache_dir instead of temp dir so subprocesses can access files
801
+ CompilerBisector.in_process_cache = cache_dir()
802
+ result = bisection_manager.do_bisect(test_function, cli_interface=False)
803
+ if result:
804
+ print(f"\nBisection complete: {result}")
805
+ else:
806
+ print("\nBisection complete: no issue found")
807
+ sys.exit(0)
808
+
809
+ if command not in ["good", "bad"]:
810
+ print(f"Invalid command: {command}")
811
+ print("Must be 'good', 'bad', 'start', 'end', or 'run'.")
812
+ sys.exit(1)
813
+
814
+ def test_function() -> bool:
815
+ return command == "good"
816
+
817
+ if not bisection_manager.get_backend():
818
+ raise ValueError("Must call start prior to good or bad")
819
+
820
+ bisection_manager.do_bisect(test_function, cli_interface=True)
821
+
822
+
823
+ def get_is_bisection_enabled() -> bool:
824
+ return (
825
+ CompilerBisector.get_subsystem() is not None
826
+ or CompilerBisector.get_backend() is not None
827
+ )
828
+
829
+
830
+ CompilerBisector.bisection_enabled = get_is_bisection_enabled()
831
+
832
+ if __name__ == "__main__":
833
+ command_line_usage()